【问题标题】:How to execute more then one query in a prepared statement?如何在准备好的语句中执行多个查询?
【发布时间】:2020-06-23 16:12:21
【问题描述】:

我使用准备好的语句执行了一个查询,现在我想在 while 循环中执行另一个查询。但它给了我一个错误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); ?>

【问题讨论】:

  • 你的哪一行代码失败了?
  • @PaulSpiegel,我的第二个查询没有执行?
  • 见:Buffered and Unbuffered queries。但我认为您可以通过单个查询获得相同的结果。第二个查询中的$post_id 是什么?
  • @PaulSpiegel $post_id 是从第一个查询中获取的,它不能是静态的,所以我需要在第一个查询中执行第二个查询。但是如何在准备好的语句中启用缓冲?

标签: php mysql mysqli prepared-statement


【解决方案1】:

PHP (mysqli) 默认使用缓冲查询。这意味着从 MySQL 服务器中一一获取行。在获取最后一行或显式释放结果之前,您无法执行任何其他查询。如果您想使用无缓冲查询,请阅读documentation。但我宁愿使用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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 2020-03-15
    • 2012-02-16
    • 1970-01-01
    相关资源
    最近更新 更多