Programmer4000
Programmer4000

Reputation: 31

Display images from a database into a PHP page

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

Upvotes: 0

Views: 74

Answers (3)

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111839

You should change

$array = array($URL);

into

$array[] = $URL;

And add before line:

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

add line:

$array = array();

Upvotes: 1

Ian
Ian

Reputation: 3676

$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

Upvotes: 1

Krish R
Krish R

Reputation: 22711

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>';
    }

Upvotes: 1

Related Questions