我遇到了最奇怪的 PHP PDO 问题,希望你们能帮我解决。
如果我将 $checkLimit
设置为 50000,则查询工作正常。但是,如果我将它设置为任何高于 50k 的值,它不会返回任何结果 - 也不会转换任何错误消息(我已经使用 $db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING)
。
$sql = "
SELECT d_domain_name AS domainName, d_domain_id AS domainID
FROM domains
ORDER BY d_domain_name_length ASC, d_domain_name ASC
LIMIT :checkLimit
";
$stmt = $db->prepare($sql);
$stmt->bindValue(':checkLimit', intval($checkLimit), PDO::PARAM_INT);
$stmt->execute();
$results = $stmt->fetchAll();
foreach ($results as $result) {
// 50k moments of magic
}
如果我在 PHP 之外运行查询,它可以在任何限制下工作(即使是 500k,也需要大约 3 分钟)。
我尝试按顺序将 $results = $stmt->fetchAll()
更改为 while ($result = $stmt->fetch()) {}
试图节省内存,但不幸的是,这没有做任何事情。
谁能告诉我我做错了什么?我错过了什么?为什么我不能超过 50k?
最佳答案
引用:http://php.net/manual/en/mysqlinfo.concepts.buffering.php
PDO 默认使用“缓冲查询”。
This means that query results are immediately transferred from the MySQL Server to PHP in is then kept in the memory of the PHP process. .... The downside of the buffered mode is that larger result sets might require quite a lot memory. ....
Following these characteristics buffered queries should be used in cases where you expect only a limited result set or need to know the amount of returned rows before reading all rows. Unbuffered mode should be used when you expect larger results.
50k 是一个很大的结果集。您可以尝试让 pdo 使用无缓冲模式并一次获取一行吗?这是从引用中复制的示例。第 2 行设置非缓冲模式。
<?php
$pdo = new PDO("mysql:host=localhost;dbname=world", 'my_user', 'my_pass');
$pdo->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$uresult = $pdo->query("SELECT Name FROM City");
if ($uresult) {
while ($row = $uresult->fetch(PDO::FETCH_ASSOC)) {
echo $row['Name'] . PHP_EOL;
}
}
?>
关于当 LIMIT 太高时,PHP 的 PDO 查询不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15580440/