問題描述
假設我有這樣的事情:
$db=new PDO($dsn);
$statement=$db->query('Select * from foo');
while ($result=$statement->fetch())
{
//do something with $result
}
我如何在 while 循環中放置另一個查詢?即使我創建了一個新的 PDOStatement 對象,它似乎也會覆蓋最頂層 PDO 語句的游標.我看到的唯一其他解決方案是 a) 一次獲取整個外部循環或 b) 打開 2 個不同的數據庫連接.這些似乎都不是一個好主意,還有其他解決方案嗎?
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?
推薦答案
你應該能夠在你的 while 循環中執行任何你想要的其他查詢,我想說;像這樣:
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...
盡管如此,如果可以(如果您的數據沒問題,我的意思是),使用 JOIN 僅執行一個查詢可能會提高性能:1 個查詢而不是多個查詢通常更快.
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 和嵌套獲取的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!