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 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集