PDO和嵌套提取 [英] PDO and nested fetching

查看:100
本文介绍了PDO和嵌套提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的:

  $ db = new PDO($ dsn); 

$ statement = $ db-> query('Select * from foo');

while($ result = $ statement-> fetch())
{
//使用$ result执行操作
}

如何将另一个查询放在while循环中?即使我创建了一个新的PDOStatement对象,它似乎覆盖了最上面的PDO语句的游标。我看到的唯一的其他解决方案是a)一次获取整个外部循环或b)打开2个不同的连接到数据库。

解决方案

你应该能够做任何其他查询想在你的while循环,我会说;像这样:

  $ db = new PDO($ dsn); 

$ statement = $ db-> query('Select * from foo');

while($ result = $ statement-> fetch())
{
$ statement2 = $ db-> query('Select * from bar');
while($ result2 = $ statement2-> fetch()){
//使用result2
}
}
pre>

您尝试过吗?它应该工作...





仍然,如果你可以(如果你的数据没关系,我的意思),使用JOIN只有一个查询可能更好的性能:1查询,而不是几个通常更快。


Let's say I have something like this:

$db=new PDO($dsn);

$statement=$db->query('Select * from foo');

while ($result=$statement->fetch())
{
    //do something with $result
}

How would I put another query inside of that while loop? Even if I make a new PDOStatement object, it seems that that overwrites the cursor for the topmost PDO statement. The only other solution I see is to either a) fetch the entire outer loop at once or b) open 2 different connections to the database. Neither of these seem like a good idea, are there any other solutions?

解决方案

You should be able to do any other query you want inside your while loop, I'd say ; something like this :

$db=new PDO($dsn);

$statement=$db->query('Select * from foo');

while ($result=$statement->fetch())
{
    $statement2 = $db->query('Select * from bar');
    while ($result2=$statement2->fetch()) {
        // use result2
    }
}

Did you try that ? It should work...


Still, if you can (if it's OK with your data, I mean), using a JOIN to do only one query might be better for performances : 1 query instead of several is generally faster.

这篇关于PDO和嵌套提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆