Reputation: 23
I am using PHP, HTML, and MySQL to build a website.
So, my goal is to make an image gallery for my webpage which should display only 3 images each row.
But my code seems wrong and I do not know where should I do the correction.
-) Here is my code:
$query = mysql_query("SELECT DISTINCT * FROM products WHERE catID = 11 ORDER BY typeID ASC");
echo "<table>";
while ($row = mysql_fetch_assoc($query))
{
echo "<tr>";
for ($c = 0; $c < 3; $c += 1){
echo "<td>";
echo '<img src="data:image/jpg;base64,'.base64_encode($row['productImg'] ).'" width="300" height="200" alt=""
/>';
echo "<br>";
echo "<b>";
echo $row['productName'];
echo "</b>";
echo "<br>";
// More detail button set up
?><a href="show.php?productID=<?php echo $row["productID"]; ?>">More Detail <i class="fa fa-arrow-circle-o-right"></i></a> <?php
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
-) Here is the result: wrong result image
The result turns out not what I expected since on 1 row it displays 3 same images. What I wanted is to display 3 different images on each row. I do not know where I did wrong.
Upvotes: 1
Views: 64
Reputation: 16963
The result turns out not what I expected since on 1 row it displays 3 same images.
That's because of the for
loop, you are looping through the same image three times. Instead use a counter variable $counter
to track number of iterations and display three different images per row.
<?php
$query = mysql_query("SELECT DISTINCT * FROM products WHERE catID = 11 ORDER BY typeID ASC");
if(mysql_num_rows($query)){
$counter = 0;
echo "<table><tr>";
while ($row = mysql_fetch_assoc($query)) {
if($counter != 0 && $counter % 3 == 0){
echo "</tr><tr>";
}
echo "<td>";
echo '<img src="data:image/jpg;base64,'.base64_encode($row['productImg'] ).'" width="300" height="200" alt=""/>';
echo "<br>";
echo "<b>";
echo $row['productName'];
echo "</b>";
echo "<br>";
// More detail button set up
?>
<a href="show.php?productID=<?php echo $row["productID"]; ?>">More Detail <i class="fa fa-arrow-circle-o-right"></i></a>
<?php
echo "</td>";
++$counter;
}
echo "</tr></table>";
}
?>
Sidenote: Don't use mysql_*
functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli
or pdo
instead. And this is why you shouldn't use mysql_*
functions.
Upvotes: 1