繁体   English   中英

如何在准备好的语句中执行多个查询?

[英]How to execute more then one query in a prepared statement?

我使用准备好的语句执行了一个查询,现在我想在 while 循环中执行另一个查询。 但是它给了我一个Commands out of sync; you can't run this command now Commands out of sync; you can't run this command now 如何解决这个问题?

<?php
$query = "SELECT post_id, post_title, post_author, post_date, post_image, post_content, post_tags FROM posts WHERE post_status = ? LIMIT ?, ?";
$stmt = mysqli_prepare($connection, $query);
if (!$stmt) {
  echo "Mysql error";
} else {
  mysqli_stmt_bind_param($stmt, "sii", $db_post_status, $page_1, $per_page);

  $db_post_status = "Published";

  mysqli_stmt_execute($stmt);
  mysqli_stmt_bind_result($stmt, $post_id, $post_title, $post_author, $post_date, $post_image, $post_content, $post_tags);
}                  

while (mysqli_stmt_fetch($stmt)) {

?>

   //// Some HTML code ////
   
<?php
  $query = "SELECT like_count FROM likes WHERE like_post_id = $post_id ";
  $sendQuery = mysqli_query($connection, $query);
  $likes = mysqli_num_rows($sendQuery);
?>
   
  //// Some HTML code ////
   
<?php } mysqli_stmt_close($stmt); ?>

PHP (mysqli) 默认使用缓冲查询。 这意味着从 MySQL 服务器逐一获取行。 在获取最后一行或显式释放结果之前,您无法执行任何其他查询。 如果您想使用无缓冲查询,请阅读 文档 但我宁愿使用fetch_all()一次获取所有行,然后使用foreach获取的行。 或者甚至更好地将单个查询与第二个查询一起用作相关子查询:

$query = "
    SELECT
      post_id,
      post_title,
      post_author,
      post_date,
      post_image,
      post_content,
      post_tags,
      (SELECT like_count FROM likes WHERE like_post_id = post.post_id) as like_count
    FROM posts
    WHERE post_status = ?
    LIMIT ?, ?
";

然后在bind_result()中包含$like_count

mysqli_stmt_bind_result($stmt, $post_id, ... , $post_tags, $like_count);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM