我想在页面中打印一个包含3列building name
,tags
和architecture style
的简单表格。如果我尝试检索building names
和arch. styles
的列表,则没有问题:
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.
我该怎么做才能避免这种情况?我应该更改所有内容并以不同的方式搜索以获得此类查询吗?
答案 0 :(得分:3)
您说您发布了代码的简化版本。你在这里贴出来的时候有什么改变吗?当您同时“打开”多个查询时,通常会导致此错误。例如,您调用了fetch()
,但是在它耗尽之前您不会调用它,然后您尝试检索第二个查询。
根据您的上述代码判断,这不应该发生,因为您使用的是fetchAll()
。通常,此问题的解决方案是致电closeCursor()
[docs]。您可以尝试在每个fetchAll
之后调用它,看看是否有任何效果。
答案 1 :(得分:1)
在循环中你实际上是再次获取第一个语句(注意
$buildings_stmt->fetchAll()
致电):
$tags_stmt->execute ();
$tags = $buildings_stmt->fetchAll (PDO::FETCH_ASSOC);
您可能想要做的是获取$tags_stmt
语句?
$tags_stmt->execute ();
$tags = $tags_stmt->fetchAll (PDO::FETCH_ASSOC);