Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

php - PDO and nested fetching

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...