問題描述
我有這個示例查詢:
$STH = $DBH->query("SELECT id FROM table");
我想獲取第一行,然后循環顯示所有行.所以我使用以下內容來獲取第一行:
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
我使用 while 循環再次顯示所有行:
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
現在 while 跳過第一行,我希望它被顯示.是否有等效于 mysql_data_seek
將指針再次重置到第一行?我知道 fetchall
可以使用,但它對內存很不利,而且很浪費.我也可以運行查詢并限制為 1,但不建議這樣做,因為我有一個連接多個表的查詢,并且速度非常慢.還有其他解決辦法嗎?
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek
to reset the pointer again to the first row? I know fetchall
can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
謝謝
推薦答案
我認為你可以使用光標方向常量來選擇結果......示例代碼即將推出......我還沒有嘗試過,所以你可以需要玩一會兒.這也是基于這樣一個假設:PDO::FETCH_ORI_FIRST
的作用類似于 data_seek,并將光標留在第一個位置,而不是將其返回到之前的位置.
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST
acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
<小時>
我不認為你可以倒帶一個語句......假設這些塊沒有被一堆中間邏輯 id 分開,只需在循環中進行即可.
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
這篇關于如何在沒有 FETCHALL 的情況下在 MYSQL PDO 中獲取 2 次的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!