Adam Kona Adam Kona - 1 year ago 59
PHP Question

How do I store images from an sql query under different variables if they all have the same id?

My problem is that I'm developing a property website that stores multiple imaages of a property in a different table to the one that stores the information about the table. I use the property_id from the properties table as a foreign key in the images table. However I want to retrieve all these images and store them as different variables for use elsewhere where I display these images in a slider. The code I'm using to retrieve the images is:

$image_result=mysqli_query($con,"SELECT * FROM tbl_images
WHERE property_id ='$id' ");

while($row_i = mysqli_fetch_array($image_result))
$image = $row_i['image'];
$property_display = cl_image_tag($image,
array( "width" => 800, "height" => 600, "crop" => "fill" ));


I can't think of how to get separate variables for each of the different images, as they each have the same property id. Where I want to use these variables is here:

<img class="mySlides" src="<HERE>" style="width:100%">

Any help would be appreciated

Answer Source

After a chat...

Expanding on your code, here's the PHP to get the data,

// prepare array to hold image data
$property_display = [];

// query
$image_result = mysqli_query($con,"SELECT * FROM tbl_images WHERE property_id ='$id' ");

// process results
while($row_i = mysqli_fetch_array($image_result)) {   
    // get the image name 
    $image_name = $row_i['image_name'];
    // note the [] here - adding a new element to the array
    $property_display[] = cl_image_tag($image_name, 
                array( "width" => 800, "height" => 600, "crop" => "fill" ));


and here's getting the data (also checking for no images)

if ($property_display) {
    // iterate over array
    foreach ($property_display as $image) {
        // echo the image tag stored in the array
        echo $image;
} else {
    echo 'No property images!';

Quite basic but should hopefully give you what you need.

On a side note have a look at PDO ( - this should really be the way you interact with your database. Especially to avoid SQL injection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download