How to display image albums in posts? [using PHP and MYSQL only]

后端 未结 1 1937
梦谈多话
梦谈多话 2021-01-24 11:12

I\'m new to php and mysql programming and new to this forum. I have a major problem with my website project. I\'ve searched the whole internet for a solution, with no success. I

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-24 11:27

    Your first SQL query is fine, but for the second one, you only want to select the images for the current post (row) in the outer while loop, so the second SQL query should be:

    "SELECT img_file, img_title FROM images WHERE post_id = $row[id_post]"
    

    Update for showing only img3 of post1:

    
    
    
    ";
         echo $row['post_title'];
         echo "
    "; if ($row['id_post'] == 1) { $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']. " AND img_title = 'img3'"); } else { $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']); } if(mysqli_num_rows($resultx) > 0) { while ($rowx = mysqli_fetch_array($resultx)) { echo ""; echo $rowx['img_title']; } } echo "
    "; echo "
    "; } ?>

    I've placed the second SQL query in an if statement, which checks if the id of the current post is equal to 1. If it is, then the SQL query only selects the row with "img3" in it. (And if it's not it executes the previous SQL query which selects all the rows.)

    Of course this only works if you know the id of the post and the title of the image that you want to display. A more generic solution for always displaying only the third image of the first post would be something like this:

    
    
    
     $value)
       echo "
    "; echo $row['post_title']; echo "
    "; if ($key == 0) { $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']. " ORDER BY id_img LIMIT 1 OFFSET 2"); } else { $resultx = mysqli_query($db, "SELECT img_file, img_title FROM images WHERE post_id = " .$row['id_post']); } if(mysqli_num_rows($resultx) > 0) { while ($rowx = mysqli_fetch_array($resultx)) { echo ""; echo $rowx['img_title']; } } echo "
    "; echo "
    "; } ?>

    Here I've stored the entire result of the first SQL query in an array, because then the keys of the array correspond with the number of each post minus one. If $key = 0, the current row is the first post and then we use the SQL query that selects only the third image from the images table. If $key isn't 0 we use the other SQL query that selects all of the images.

    In the new SQL query, LIMIT 1 means select 1 row only, and OFFSET 2 means start with row 3 (counting starts at 0, so offset 2 returns row 3).

    I've added ORDER BY id_img to make sure images are always returned in the same order, the order in which they were added to the database. (And I've done the same with id_post in the first query.)

0 讨论(0)
提交回复
热议问题