I use the following code to retrieve data from my database. The problem is that it only displays the first row. In this particular case, it means that only the first picture is shown on the webpage but I want to show all of them.
<?php
$sql = "SELECT `image-id`, `article-id`, `image-path`, `image-title` FROM `table-images` WHERE `article-id` = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$stmt->execute();
if($result = $stmt->fetch(PDO::FETCH_ASSOC))
{
?>
<a class="swipebox" href="<?php echo $result['image-path'];?>" title="<?php echo $result['image-title'];?>">
<img alt="image" src="<?php echo $result['image-path'];?>"></a>
<?php
}// end if
else {
echo '0 results';
}// end else
?>
I read this article so I tried to use the code:
if($result = $stmt->fetchAll(PDO::FETCH_ASSOC));?
... but that doesn't work. It doesn't even echo the first picture anymore. What am I missing here?
Here is how it works:
$stmt = $pdo->prepare($sql);
$stmt->bindParam(":id", $id);
$success = $stmt->execute();
if($success){
//fetch here
}
Now you have 2 options for fetching the data:
fetch()
fetch()
will get rows one by one so you need a while loop.
while($rows = $stmt->fetch(PDO::FETCH_ASSOC)){
// get data
}
fetchAll()
fetchAll()
get all the rows at once so no need for loops to retrieve the data, but if you need to loop then you will need a for loop.
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($rows as $row){
//do something
}