PHP 的 PDO 准备方法在循环中失败
给出以下代码:
// Connect to MySQL up here
$example_query = $database->prepare('SELECT * FROM table2');
if ($example_query === false) die('prepare failed');
$query = $database->prepare('SELECT * FROM table1');
$query->execute();
while ($results = $query->fetch())
{
$example_query = $database->prepare('SELECT * FROM table2');
if ($example_query === false) die('prepare failed'); //it will die here
}
我显然尝试准备语句来 SELECT 表 2 中的所有内容两次。 第二个(WHILE 循环中的那个)总是失败并导致错误。
这仅在我的生产服务器上,在本地开发我没有问题,所以它一定是某种设置。
我立即想到的是,MySQL 有某种 max_connections 设置,该设置设置为 1,并且连接保持打开状态,直到 WHILE 循环完成,因此当我尝试准备新查询时,它会说“不,已经连接太多了”,然后就退出了。
有任何想法吗?
编辑:是的,我知道没有必要做两次,在我的实际代码中,它只在 WHILE 循环中准备好,但就像我说的那样,在我的生产服务器上失败了,所以经过一些测试后我发现简单的 SELECT * 查询在 WHILE 循环中失败,但在循环外不会失败。 我给出的示例代码显然是非常淡化的,只是为了说明问题。
Given the following code:
// Connect to MySQL up here
$example_query = $database->prepare('SELECT * FROM table2');
if ($example_query === false) die('prepare failed');
$query = $database->prepare('SELECT * FROM table1');
$query->execute();
while ($results = $query->fetch())
{
$example_query = $database->prepare('SELECT * FROM table2');
if ($example_query === false) die('prepare failed'); //it will die here
}
I obviously attempt to prepare statements to SELET everything from table2 twice. The second one (the one in the WHILE loop) always fails and causes an error.
This is only on my production server, developing locally I have no issues so it must be some kind of setting somewhere.
My immediate thought is that MySQL has some kind of max_connections setting that is set to 1 and a connection is kept open until the WHILE loop is completed so when I try to prepare a new query it says "nope too many connected already" and shits out.
Any ideas?
EDIT: Yes I know there's no need to do it twice, in my actual code it only gets prepared in the WHILE loop, but like I said that fails on my production server so after some testing I discovered that a simple SELECT * query fails in the WHILE loop but not out of it. The example code I gave is obviously very watered down to just illustrate the issue.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,当无缓冲查询运行时(它位于 WHILE 循环中),我无法执行某些操作。
解决方案是添加以下行以确保使用缓冲查询:
Problem was that I couldn't do something while an unbuffered query was running (which it was in the WHILE loop)
Solution was to add the following line to ensure buffered queries were being used:
不需要多次准备 $example_query。 只需在循环内执行查询即可。
编辑:如果您必须在每次循环迭代中准备一个新查询,则循环结束时的显式 $example_query->closeCursor() 应释放与语句对象关联的任何资源。
There shouldn't be a need to prepare $example_query more than once. Simply execute the query inside your loop.
EDIT: If you must prepare a new query in each loop iteration, an explicit $example_query->closeCursor() at the end of the loop should free any resources associated with the statement object.