phpfor-loop

PHP rows to variables


I want to make a dynamic gallery taking the images names and locations (folders where they are in) from a database. Gallery would have always 15 photos (the last entry's in the db) so I need to save the images directory and names into variables to pass them to the HTML for the carousel.

I have a column "álbum_name" with the name of the álbum (folder where the image is in) and another called "img_name" which has the imagenames.jpg, so I need to add a / between them. I was thinking of something like:

$sql = "SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15";
$result = mysqli_query($conn, $sql);

$photo0;
$photo1;
$photo2;
$photo3;
$photo4;
$photo5;
$photo6;
$photo7;
$photo8;
$photo9;
$photo10;
$photo11;
$photo12;
$photo13;
$photo14;

$img_num = mysqli_num_rows($result );

for ($i = 0; $i < $img_num ; $i++) {
// and here something to pass for each row álbum_name . "/" . img_name to the variables.
}

I was looking that for this things PHP man use while and fech_array or fech_row, but they don't do what I'm trying to...

Thanks.


Solution

  • You should have a look to the arrays

    It is very easy to get an array of results, see this example (code not tested, but it should work):

    <?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");  // Create a connection
    
    $mysqli->query("SELECT album_name, img_name FROM gallery WHERE status = 1 ORDER by date DESC LIMIT 15");      // Perform the query
    
    $gallery = $mysqli->fetch_array(MYSQLI_ASSOC); // Get the results. MYSQLI_ASSOC is used here to return an associative array with the name of each table field
    

    That's it! You can see what's inside your array $gallery

    <?php
    echo '<pre>';
    var_dump($gallery);
    echo '</pre'>;
    

    And you can iterate it without using any counter with a foreach! :D

    <?php
    foreach ($gallery as $image) {
        echo '<p>Album name:'.$image['album_name'].'</p>';
        echo '<img src="/images/'.img_name.'/>"';
    }