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

倾然丶 夕夏残阳落幕 提交于 2019-12-04 05:44:35

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/26367359/how-to-run-an-sql-query-inside-a-while-loop-of-another-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!