Reputation: 811
I am a little confused on when you use the fetch() method and when you do not. Like in this case:
Why do I need the fetch() method here:
$query = "SELECT * FROM Idea_Categories WHERE categoryID = $category_id";
$category = $db->query($query);
$category = $category->fetch();
$category_id = $category['categoryID'];
$category_name = $category['categoryName'];
But not here:
$query = "SELECT * FROM statements WHERE categoryID = $category_id ORDER BY entryID";
$statements = $db->query($query);
I use $statements here and it just lists all the statements I have in the database:
<table>
<?php foreach ($statements as $statement) :?>
<tr>
<td><?php echo $statement['topic']; ?></td>
<td>
<form action="delete_line.php" method="post">
<input type="hidden" name="topic" value="<?php echo $statement['topic'];?>" />
<input type="hidden" name="category_id" value="<?php echo $statement['categoryID'];?>" />
<input type="submit" value="Delete" />
</form>
</td>
<td>
<form action="product_rate.php" method="post">
<input type="hidden" name="topic" value="<?php echo $statement['topic'];?>" />
<input type="submit" value="Upvote" name="action" />
</form>
</td>
<td>
<form action="product_rate.php" method="post">
<input type="hidden" name="topic" value="<?php echo $statement['topic'];?>" />
<input type="submit" value="Downvote" name="action"/>
</form>
</td>
</tr>
<?php endforeach; ?>
Upvotes: 0
Views: 91
Reputation: 522523
PDO::query
returns a PDOStatement
object. Any time you are handling a result set with PDO you have such an object. Usually you call PDOStatement::fetch
on it to get the results, often in a loop like this:
while ($row = $stmt->fetch()) ...
PDOStatement
also implements the Traversable
interface though, which simply enables you to do exactly the same thing as above, but using foreach
:
foreach ($stmt as $row) ...
It's just a bit of syntactic sugar thanks to the Traversable
interface, which you can implement in any of your own classes as well.
Upvotes: 1