doumisha5081 2013-03-19 14:10
浏览 51
已采纳

多个预准备语句(SELECT)

I'm trying to change my SQL queries with prepared statements. The idea: I'm getting multiple records out of the database with a while loop and then some additional data from the database in the loop.

This is my old SQL code (simplified):

$qry = "SELECT postId,title,userid from post WHERE id='$id'"; 
$rst01 = mysqli_query($mysqli, $qry01);
// loop trough mutiple results/records
while (list($postId,$title,$userid) = mysqli_fetch_array($rst01)) {
// second query to select additional data
$query05 = "SELECT name FROM users WHERE id='$userid";
$result05 = mysqli_query($mysqli, $query05);
$row05 = mysqli_fetch_array($result05);
$name = $row05[name ];

echo "Name: ".$name;

// do more stuff

// end of while loop
}

Now I want to rewrite this with prepared statements. My question: is it possible to run a prepared statement in the fetch of another prepared statement ? I still need the name like in the old SQL code I do for the $name.

This is what've written so far.

$stmt0 = $mysqli->stmt_init();
$stmt0->prepare("SELECT postId,title,userid from post WHERE id=?"); 
$stmt0->bind_param('i', $id);
$stmt0->execute();
$stmt0->bind_result($postId,$title,$userid);
// prepare second statement
$stmt1 = $mysqli->stmt_init();
$stmt1->prepare("SELECT name FROM users WHERE id= ?");
while($stmt0->fetch()) {

$stmt1->bind_param('i', $userid);
$stmt1->execute();
$res1 = $stmt1->get_result();
$row1 = $res1->fetch_assoc();

echo "Name: ".$row1['name'] ;

}

It returns an error for the second statement in the loop:

 Warning: mysqli_stmt::bind_param(): invalid object or resource mysqli_stmt in ... 

If I use the old method for the loop and just the prepared statement to fetch the $name it works.

  • 写回答

1条回答 默认 最新

  • duangu4980 2013-03-19 14:15
    关注

    You can actually do this with a single JOINed query:

    SELECT p.postId, p.title, p.userid, u.name AS username
    FROM post p
    JOIN users u ON u.id = p.userid
    WHERE p.id = ?
    

    In general, if you are running a query in a loop, there is probably a better way of doing it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀