Classes for view file?
I am not sure how to explain in detail but I will try my best.
Currenly I have a php file it look something like this:
$SQL_Cat = mysql_query("SELECT * FROM categories WHERE restaurant_id = '$restaurantID'");
while ($category = mysql_fetch_array($SQL_Cat))
{
$CategoryID = $category['id'];
echo $category['name'];
$q = mysql_query("SELECT * FROM items WHERE category_id = '" . $CategoryID . "'");
while($item = mysql_fetch_array($q))
{
$item_name = $item['name'];
echo $item_name;
}
}
As you can see there are $category and $item ,how to create this class (classname/{Category, Item}) to use the view. Example below:
<?php foreach($categories as $category): ?>
<table border=0 Cellspacing='0'>
<tr>
<td>
<?php echo $category->name; ?>
</td>
</tr>
<?php foreach ($category->items as $item): ?>
<tr>
<td>
<?php echo $item->name; ?>
</td>
开发者_StackOverflow社区 </tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
So I can keep SQL queries away from a view file.
$SQL_Cat = mysql_query("SELECT * FROM categories WHERE restaurant_id = '$restaurantID'");
while ($category = mysql_fetch_object($SQL_Cat))
{
$category->items = array();
$q = mysql_query("SELECT * FROM items WHERE category_id = '" . $category->id . "'");
while($item = mysql_fetch_object($q))
{
$category->items[] = $item;
}
$categories[] = $category;
}
Use PDO and fetch it into an object. PDO is capable of automatically constructing objects so you don't have to write class definitions.
精彩评论