gpt4 book ai didi

php - 使用绝对位置游标的 PDO pgsql 获取失败

转载 作者:行者123 更新时间:2023-11-29 14:02:13 25 4
gpt4 key购买 nike

我正在尝试使用 PDO 创建游标的能力来实现分页功能。

目前,我的代码看起来有点像这样(非常复杂,我知道):

$pdo = new PDO();
$pdo->setAttribute(PDO::ATTR_CURSOR, PDO::CURSOR_SCROLL);
// prepared select-query omitted
$pdoStatement = $pdo->execute();

$start_index = MAX_THINGS_PER_PAGE * $current_page - MAX_THINGS_PER_PAGE;
$stop_index = MAX_THINGS_PER_PAGE * $current_page;
$row_count = $this->statement->rowCount(); // works for the PgSQL driver
$index = $start_index;
while (($row_count > 0) && ($index < $stop_index))
{
// try-catch block omitted
$values[] = $this->statement->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_ABS, $index);

--$row_count;
++$index;
}

但是,从表面上看,无论$start_index 是什么,查询都只会获取结果集的前 10 行(即 MAX_THINGS_PER_PAGE 的值)行。总是。

可能我做错了什么,但是使用游标进行分页的艺术似乎有些神秘而且没有记录......

最佳答案

我今天刚遇到这个问题。 PDOStatement::rowCount() 不适用于某些数据库上的 SELECT。来自 PDOStatement::rowCount :

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

我花了很多时间才意识到这一点,因为我认为这是使用游标的问题。

这是我采用的方法:将 PDOStatement::rowCount() 的使用替换为以下内容:

<?php
$row_count = count($stmt->fetchAll());
?>

它在内存方面效率不高,但这是许多数据库用来计算总行数的方法。

关于php - 使用绝对位置游标的 PDO pgsql 获取失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7504426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com