我有两个预准备语句(例如),其中第二个语句将在while(stmt1->fetch()){}
循环中执行。但是,内部语句(stmt2)不会在第一个while循环中执行:
<?php
$mysqli = new mysqli("localhost","root","","test");
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
$stmt1 = $mysqli->prepare("select id from posts");
$stmt2 = $mysqli->prepare("select username from members where id=?");
$stmt1->execute();
$stmt1->bind_result($ID);
while($stmt1->fetch())
{
echo $ID.' ';
/*Inner query*/
$stmt2->bind_param('i',$id);
$id =$ID;
$stmt2->execute();
$stmt2->bind_result($username);
while($stmt2->fetch())
{
echo 'Username: '.$username;
}
/*Inner query ends*/
}
?>
如果我将内部查询部分剪切粘贴到外部while循环之外,它会执行,但它没用。我该怎么做才能正确执行它?
答案 0 :(得分:0)
为什么嵌套循环,当你可以改为 INNER JOIN 时。
<?php
$mysqli = new mysqli("localhost","root","","test");
if(mysqli_connect_errno())
{
printf("connection failed: %s\n",mysqli_connect_error());
exit();
}
if($stmt1 = $mysqli->prepare("SELECT posts.id,members.username FROM posts INNER JOIN members ON posts.id=members.id")){
$stmt1->execute();
$stmt1->bind_result($id,$username);
while($stmt1->fetch()){
printf("ID # %d.<br>Username: %s<br><br>",$id,$username);
}
$stmt1->close();
}
$mysqli->close();
?>