0

Im wondering what can I do to make images from a database on Php display on my page. This is what I have

images .php

$query = "SELECT * FROM images ORDER BY name ASC ";

            $result = $db->query($query);
            $num_result = $result->num_rows;

            echo "<h1> Images</h1>";

            for ($i = 0; $i < $num_result; $i++){

                $row = $result->fetch_assoc();
                $name = $row['name'];
                $URL = $row['imageURL'];


                $array = array($URL);
            }

foreach ($array as $image){
        echo '<tr>';
        echo '<td><img class="coupons" src="'.$image.'"/></td>';
        echo '<td></td>';
        echo '</tr>';
        echo '<tr>';

          }  

This is just printing only one image and I have 10 in my database, what can I do or change to print all of the images from the database? Thanks

3 Answers 3

1

You should change

$array = array($URL);

into

$array[] = $URL;

And add before line:

for ($i = 0; $i < $num_result; $i++){

add line:

$array = array();
Sign up to request clarification or add additional context in comments.

3 Comments

don't forget to assign your array before the for loop unless you like errors.
True, I've added info to answer
this worked great! thanks a lot and yeh added the $array = array(); at the top
1

Try this,

$array = array();//initialize here 
for ($i = 0; $i < $num_result; $i++){
            $row = $result->fetch_assoc();
            $name = $row['name'];
            $URL = $row['imageURL'];
            $array[] = $URL;
    }

You can rewrite your code as,

    while ($row = $result->fetch_assoc()){
        $name = $row['name'];
        $URL = $row['imageURL'];    
        echo '<tr>';
        echo '<td><img class="coupons" src="'.$URL.'"/></td>';
        echo '<td></td>';
        echo '</tr>';
        echo '<tr>';
    }

Comments

1
$query = "SELECT * FROM images ORDER BY name ASC ";

$result = $db->query($query);
$num_result = $result->num_rows;

$array = array();

echo "<h1> Images</h1>";

for ($i = 0; $i < $num_result; $i++){

    $row = $result->fetch_assoc();
    $name = $row['name'];
    $URL = $row['imageURL'];


    $array[] = URL;
}

foreach ($array as $image){
    echo '<tr>';
    echo '<td><img class="coupons" src="'.$image.'"/></td>';
    echo '<td></td>';
    echo '</tr>';
}

You also had a trailing <tr> which may cause styling issues

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.