如何遍历 PDOStatement 对象,即获取第一个、最后一个、上一个、下一个等?
我试图在网页中一次又一次地访问数据。有更好的办法吗?像 movetofirst()、movetolast()、movetoprevious()、movetonext() 这样的东西可能会很好。
现在我正在将结果集作为数组检索(使用 fetchall())并一次又一次地重新使用该数组。
有像下面这样的事情要做吗?我不需要一次又一次地执行查询。如果结果/数组有数百行,则将数据保存在数组中并消耗资源。
$sql = 'SELECT cityname, statename FROM TBLPLACES ORDER BY cityname, statename';
$stmt = $conn->query($sql);
if ($stmt) {
while($row=$stmt->fetch()){
// do some thing
}
// do some more thing
//
// now here, can i access same $stmt object
// to fetch resultset again without executing
// $stmt = $conn->query($sql); again ?
// (no change in query sql, need to fetch the same static data again.)
//
// something like below will be nice.
//
// $stmt->movetofirst();
// while($row=$stmt->fetch()){
// do some thing;
// }
}
I am trying to access data again and again in a webpage. Is there a better way ? some thing like movetofirst(), movetolast(), movetoprevious(), movetonext() could be nice.
right now i am retrieving the resultset as an array (using fetchall()) and resusing the array again and again.
Is there something like below be done? I need not execute the query again and again. keep the data in a array and consume resources if the result/array is of many hundred rows.
$sql = 'SELECT cityname, statename FROM TBLPLACES ORDER BY cityname, statename';
$stmt = $conn->query($sql);
if ($stmt) {
while($row=$stmt->fetch()){
// do some thing
}
// do some more thing
//
// now here, can i access same $stmt object
// to fetch resultset again without executing
// $stmt = $conn->query($sql); again ?
// (no change in query sql, need to fetch the same static data again.)
//
// something like below will be nice.
//
// $stmt->movetofirst();
// while($row=$stmt->fetch()){
// do some thing;
// }
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要获取最后的结果,您可以执行以下操作:
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
或手动写入行号。其他
PDO::FETCH_ORI_*
常量此处,但是本质上你想更多地关注 PDOStatement::fetch() 方法。To fetch last result you can do:
$row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST);
Or write the row numbers manualy. Other
PDO::FETCH_ORI_*
constants here, but essentially you want to pay more attention to the 2nd and 3rd parameter in PDOStatement::fetch() method.只需使用
fetchAll
即可获取整个结果大批:Just use
fetchAll
to get the whole result in an array:使用 PDO,您不需要创建查询来获取上一个或下一个,
尝试 juste :
PDO::CURSOR_SCROLL
参考(示例 2):
http://php.net/manual/en/pdostatement.fetch.php
with PDO you don't need to create a query to get previous or next,
try juste :
PDO::CURSOR_SCROLL
reference (example 2):
http://php.net/manual/en/pdostatement.fetch.php