Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...