gpt4 book ai didi

php - 如何避免此 PDO 异常 : Cannot execute queries while other unbuffered queries are active

转载 作者:可可西里 更新时间:2023-11-01 06:48:18 29 4
gpt4 key购买 nike

我想在我的页面中打印一个包含 3 列的简单表格,building nametagsarchitecture style。如果我尝试检索 building namesarch 的列表。样式没有问题:

SELECT buildings.name, arch_styles.style_name
FROM buildings
INNER JOIN buildings_arch_styles
ON buildings.id = buildings_arch_styles.building_id
INNER JOIN arch_styles
ON arch_styles.id = buildings_arch_styles.arch_style_id
LIMIT 0, 10

我的问题开始于为我刚刚编写的查询的每个建筑物检索前 5 个标签。

SELECT DISTINCT name
FROM tags
INNER JOIN buildings_tags
ON buildings_tags.tag_id = tags.id
AND buildings_tags.building_id = 123
LIMIT 0, 5

查询本身运行良好,但不是我想使用它的地方:

<?php

// pdo connection allready active, i'm using mysql
$pdo_conn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);

$sql = "SELECT buildings.name, buildings.id, arch_styles.style_name
FROM buildings
INNER JOIN buildings_arch_styles
ON buildings.id = buildings_arch_styles.building_id
INNER JOIN arch_styles
ON arch_styles.id = buildings_arch_styles.arch_style_id
LIMIT 0, 10";

$buildings_stmt = $pdo_conn->prepare ($sql);
$buildings_stmt->execute ();
$buildings = $buildings_stmt->fetchAll (PDO::FETCH_ASSOC);

$sql = "SELECT DISTINCT name
FROM tags
INNER JOIN buildings_tags
ON buildings_tags.tag_id = tags.id
AND buildings_tags.building_id = :building_id
LIMIT 0, 5";
$tags_stmt = $pdo_conn->prepare ($sql);

$html = "<table>"; // i'll use it to print my table

foreach ($buildings as $building) {
$name = $building["name"];
$style = $building["style_name"];
$id = $building["id"];

$tags_stmt->bindParam (":building_id", $id, PDO::PARAM_INT);
$tags_stmt->execute (); // the problem is HERE
$tags = $tags_stmt->fetchAll (PDO::FETCH_ASSOC);

$html .= "... $name ... $style";

foreach ($tags as $current_tag) {
$tag = $current_tag["name"];
$html .= "... $tag ..."; // let's suppose this is an area of the table where I print the first 5 tags per building
}

}
$html .= "...</table>";
print $html;

我没有查询经验,所以我虽然是这样的,但它抛出了错误:

PHP Fatal error:  Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active.  Consider using PDOStatement::fetchAll().  Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

我该怎么做才能避免这种情况?我是否应该全部更改并搜索不同的方式来获取此类查询?

最佳答案

您说您发布了代码的简化版本。您在这里发布时是否更改了其他任何内容?当您同时“打开”多个查询时,通常会导致此错误。例如,您调用了 fetch(),但直到它用完才调用它,然后您尝试检索第二个查询。

根据您上面的代码判断,这不应该发生,因为您使用的是 fetchAll()。通常,此问题的解决方案是调用 closeCursor() [docs] .您可以尝试在每次 fetchAll 之后调用它,看看是否有任何作用。

关于php - 如何避免此 PDO 异常 : Cannot execute queries while other unbuffered queries are active,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2421516/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com