Reputation: 87
Using a foreach loop in php I'm trying to retrieve data from a database. The idea is to display data, such as a title, from a database using a foreach loop in order to get the data into objects / divs.
This is the database (database->posts):
I'm using a mysql query to get the data:
$db = new mysqli('localhost', 'username', 'password', 'database');
$postQuery = $db->query("
SELECT
posts.id,
posts.title
FROM posts
GROUP BY posts.id
");
while($row = $postQuery->fetch_object()){
$posts[] = $row;
}
And then I display the data using a foreach loop:
<?php foreach($posts as $post): ?>
<div><?php echo $post->title; ?>
etc.
</div>
<?php endforeach; ?>
Everything seems to work, except when I try to use the posts.id in a mysql query to check the content of the table in the databse with the corresponding posts.id. Is there a way to retrieve the id to use it in a query or php function?
Upvotes: 1
Views: 8794
Reputation: 34231
In php you can reference the ids as $post->id
within the foreach loop (following your coding convention), or $posts[x]->id
outside of the foreach loop, where x is the index of the element within the $posts array.
However, in sql you can join tables on certain fields, so you do not have to retrieve the posts.id column just to send those ids back as part of an sql request. See mysql's documentation on joins for more details.
You should remove the group by posts.id
from your query, it is redundant.
Upvotes: 2