I am storing the names and types of images in my database. Now I want to select the newest images from that database and display them to the user. I tried to use the following code but I am getting the same image name and type, but I want to get different images.
$new_image_count = mysql_query("SELECT COUNT(id) FROM newest");
$result = mysql_result($new_image_count, 0);
$select_images = mysql_query("SELECT * FROM newest");
$fetch = mysql_fetch_assoc($select_images);
for($result; $result > 0; $result--){
$name = $fetch['image_name'];
$type = $fetch['image_type'];
$name_dot_type = $name.".".$type;
echo '<img src="main_images/'.$name_dot_type.'" width="300">';
}
Any ideas about how to fix this problem ?
Remove the query to count rows (you don't need it)
and change the main part of the code to something like
$select_images = mysql_query("SELECT * FROM newest");
while ($fetch = mysql_fetch_assoc($select_images)) {
// echo data from $fetch
}
PS: you'll recently get a comments about using PDO instead of mysql_
PPS: you get the same results because you fetch the row just once, and after that you output the same values in the loop
First off, you shouldn't be using mysql_*()
functions anymore, and should switch to mysqli or PDO
Secondly, just move the $fetch = mysql_fetch_assoc($select_images);
inside the for
loop:
for($result; $result > 0; $result--){
$fetch = mysql_fetch_assoc($select_images);
$name = $fetch['image_name'];
$type = $fetch['image_type'];
$name_dot_type = $name.".".$type;
echo '<img src="main_images/'.$name_dot_type.'" width="300">';
}