PDO and nested fetching

前提是你 提交于 2019-12-29 08:25:52

问题


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?


回答1:


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.




回答2:


Sounds like what you are trying to accomplish is getting related data for the record you're looking at, why not just JOIN them in at the first query? The database will be better at connecting the dots internally than any amount of code can do externally.

But to answer your question, I don't see the harm in opening another connection to the same DSN, most likely thing to happen is that you get another instance of the PDO object pointing to the same actual connection. Also, but depending on the amount of data you're expecting you could just fetchAll and loop over a php array.



来源:https://stackoverflow.com/questions/1347955/pdo-and-nested-fetching

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!