I am trying to limit display 3 images to a row. Only a row, however, I really don't get it how to limit the number of images to display and how to display newest image to first, it's only display newest to the last row. I am trying some way, but nothing work.
Upload
<?php
if (isset($_POST['submit'])){
$target_dir = dirname(dirname(__FILE__)).'/store/';
$target = $target_dir . basename($_FILES['image']['name']);
$db = mysqli_connect("localhost", "root", "", "image");
$image = $_FILES['image']['name'];
$title = $_POST['image_title'];
$description = $_POST['description'];
$sql = "INSERT INTO images (image, title, description) VALUE ('$image', '$title', '$description')";
mysqli_query($db, $sql);
if(move_uploaded_file($_FILES['image']['tmp_name'], $target))
{
// header("location:../../gallery/gallery.html");
header("location: ../test.php");
}
}
?>
Display
<?php
$db = mysqli_connect("localhost", "root", "", "image");
$sql = "SELECT * FROM images";
$result = mysqli_query($db, $sql);
$count = 0;
while($row = mysqli_fetch_array($result)){
$listImage = $row['image'];
echo "<img src='store/".$listImage."' width='250' height='250'>";
}
You may need to update your table with an auto_increment
column or a DATETIME
column that should save the current time in the table.
Let's consider adding an auto_increment
id
field in images
table. You need to run this command to do so:
ALTER TABLE `images`
ADD `id` INT NOT NULL auto_increment first,
ADD PRIMARY KEY (`id`);
Change your SQL query to:
// to get the latest image stored in the images table.
$sql = "SELECT * FROM images ORDER BY id DESC LIMIT 1";
It will do the job for you! Also, I have added LIMIT 1
- you can change it whatever count of latest images you want
Note: If you want to get the most recent images of the last month, or you modify an image (update the date), in such cases, please consider adding a
DATETIME
column in the table and use that inorder by
clause.