Reputation: 9293
$stmt = $db->query('SELECT * FROM posts ORDER BY date DESC');
while($row = $stmt->fetch()){
$date = strtotime($row['date']);
$dateb = date("d-M-H:i", $date);
$items.= "<div class='item'" .
"data-id=" . $row['id'] . "data-path='" . $row['cats'] . "'>" .
"<span class='spandate'>" . $dateb . "</span>" .
"<span class='spantitle'>" . $row['title'] . "</span>" .
"</div>\n";
}}
This gives me a serie of item
named divs.
Now, is it possible on php side (and without writing a new SELECT statement, just using the above), to get a specific item
, i.e. item
with specific id
?
Something like:
$x = 5;
$required_item = $items(where $row['id'] == x);
Upvotes: 0
Views: 34
Reputation: 54841
Answering your primary question is:
$x = 5;
while($row = $stmt->fetch()) {
if ($row['id'] == $x) {
// do what you need - echo $row or add it to array.
}
}
But, once again - selecting all values and filter them in a php-loop is overhead.
Suppose you have thousands of rows and you need to fetch and iterate over all of them in php. Mysql query will do it much faster:
$stmt = $db->query('SELECT * FROM posts WHERE id = 5 ORDER BY date DESC');
while($row = $stmt->fetch()){
// do what you need - echo $row or add it to array.
}
So, if you want to write proper code - use mysql filtering.
Upvotes: 1