Separate controller and view from multiples queries?
I have multiple MySQL queries and I need to separate them into Controller and View (CodeIgniter framework), how is that possible? See example of codes below:
For example:
$SQL_Cat = mysql_query("SELECT * FROM categories WHERE restaurant_id = '$restaurantID'");
while ($category = mysql_fetch_array($SQL_Cat))
{
$CategoryID = $category['id'];
echo $category['name'];
if ($category['description'] != "") {
echo $category['description'];
}
$q = mysql_query("SELECT * FROM items WHERE category_id = '" . $CategoryID . "'");
while($item = mysql_fetch_array($q))
{
$item_name = $item['name'];
echo $item_name;
$item_des = $item['description'];
$sq = mysql_query("SELECT * FROM item_options WHERE item_id = '" . $item['id'] . "'");
$item_id = $item['id'];
if(mysql_num_rows($sq) > 0)
{
while($item_开发者_C百科option = mysql_fetch_array($sq))
{
echo "---------<br />";
$item_option_name = $item_option['option_value'];
$item_option_price = $item_option['price'];
$item_option_id = $item_option['id'];
echo $item_name;
echo $item_des;
echo $item_option_name;
}
}
}
}
The echo's part should be in view (MVC).
Well... The simplest way is this
controller.php
$id = $_GET[ 'id' ] ;
include_once 'model.php' ;
$content = getPage( $id ) ;
include 'view.php' ;
model.php
function getPage( $id ) {
$result = mysql_query( 'SELECT content FROM pages WHERE id = ' . intval( $id ) ) ;
$c = mysql_fetch_assoc( $result ) ;
return $c[ 'content' ] ;
}
view.php
<?= $content; ?>
Just type http://site/controller.php?id=1 in your browser (there should be en entry in you db of course)
A bit simplified but no fun in writing code scrolls :)
Check out the user guide. It really helped me understand MVC.
- Model
- View
- Controller
Once you have a good understanding of using this pattern, decomposing what you have shouldn't be too hard.
精彩评论