Mic*_*uel 5 php mysql pdo while-loop fetch
我有这个示例查询:
$STH = $DBH->query("SELECT id FROM table");
Run Code Online (Sandbox Code Playgroud)
我想得到第一行,然后循环并显示所有行.所以我使用以下内容获取第一行:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
Run Code Online (Sandbox Code Playgroud)
我使用while循环再次显示所有行:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Run Code Online (Sandbox Code Playgroud)
现在,我跳过第一行,我希望它显示出来.是否有相当于mysql_data_seek将指针再次重置到第一行?我知道fetchall可以使用,但它在内存和浪费方面都很糟糕.我也可以运行查询并限制为1,但不建议这样做,因为我有一个连接多个表的查询,并且会非常慢.还有其他解决方案吗?
谢谢
我把它看起来就像你可以使用光标方向的内容来选择结果......示例代码即将来临...我没试过这样你可能需要玩一下.这也是基于这样的假设:PDO::FETCH_ORI_FIRST像data_seek 这样的行为并将光标留在第一个位置而不是将其返回到之前的状态.
$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;
}
Run Code Online (Sandbox Code Playgroud)
我不认为你可以回复一个声明......假设这些块没有被一堆中间逻辑id分隔,只需在循环中执行即可.
$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++;
}
Run Code Online (Sandbox Code Playgroud)