I'm trying to make a dynamic gallery page for a website.
This code works fine:
After searching, I found that I can find the number of rows in a table using the
When I add a
This code works fine:
PHP:
<?php
$servername = "server";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query("SELECT title, image, link FROM gallery WHERE id=1");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<div onclick='window.location = `/gallery/image?name=" . $row['link'] . "`' class='image' style='background-image: url(data:image/jpg;charset=utf8;base64," . $row['image'] . ")'><div class='title'>" . $row['title'] . "</div></div>";
}
}
?>
After searching, I found that I can find the number of rows in a table using the
count()
function, so I have this PHP code to save the number of rows in a variable called $images
:
PHP:
$images = $conn->query("SELECT COUNT(id) FROM gallery");
When I add a
for
loop so that I can put every image in that database table on the page, it stops working:
PHP:
<?php
$servername = "server";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$images = $conn->query("SELECT COUNT(id) FROM gallery");
for ($i=0; $i < $images; $i++) {
$result = $conn->query("SELECT title, image, link FROM gallery WHERE id=$i");
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<div onclick='window.location = `/gallery/image?name=" . $row['link'] . "`' class='image' style='background-image: url(data:image/jpg;charset=utf8;base64," . $row['image'] . ")'><div class='title'>" . $row['title'] . "</div></div>";
}
}
}
?>