Relm
Relm

Reputation: 8241

How to run an sql query inside a while loop of another query

The following works with no problem at all, when the photoId is directly on the statement and not a variable.

$img_query = mysqli_query($con, 'SELECT * FROM imgs WHERE photoid = "103"') or die(mysqli_error($con));

but the following just won't work with no error, what might be causing this not to select.

$imageid = '103';
$img_query = mysqli_query($con, 'SELECT * FROM imgs WHERE photoid = "$imageid"') or die(mysqli_error($con));
$img_row = mysqli_fetch_array($img_query);
    echo $img_row['img'];

This is inside a while loop.

while($row = mysqli_fetch_array($somequery)){
 $imageid = $row['photoid'];
    $img_query = mysqli_query($con, 'SELECT * FROM imgs WHERE photoid = "$imageid"') or die(mysqli_error($con));
    $img_row = mysqli_fetch_array($img_query);
        echo $img_row['img'];
}

Thanks.

Upvotes: 0

Views: 2231

Answers (2)

Dimitri
Dimitri

Reputation: 453

there is a big difference between ' and " in php

Differences

change your query to be

$img_query = mysqli_query($con, "SELECT * FROM imgs WHERE photoid = '$imageid'") or die(mysqli_error($con));

and it should work.

Upvotes: 1

John Ruddell
John Ruddell

Reputation: 25842

in php a ' and a " are very different and the query syntax is double quote around the query and single quote around variables.. although I would recommend you look at using parameters on your query instead of just putting a variable directly into the query

Per my recommendation you should change your query to this:

$imageid = '103';
$query = $con->prepare("SELECT * FROM imgs WHERE photoid = ?");
$query->bind_param('sssd', $imageid);
$query->execute();

this is just the nuts and bolts of it... if you want more information about the connection.. error handling and everything else read the DOCS

Upvotes: 3

Related Questions