【问题标题】:php mysqli prepared statement all ways skipping the first resultphp mysqli准备语句所有方式跳过第一个结果
【发布时间】:2015-01-06 22:21:29
【问题描述】:

我有一个从数据库中获取数据的类。一切正常,但结果“剪辑”了第一个结果。 例如,我的数据库中有 15 个项目,所以通过回显我应该得到的 id

1 2 3 4 ... 13 14 15

但我明白了 2 3 4 ... 13 14 15

该语句在数据显示时有效,但为什么总是缺少第一个结果。

代码:

private function formatResults($data){
        while($row = $data->fetch(\PDO::FETCH_ASSOC)){
            echo $row['product_id'].'<br/>';
        }
    }

    public function getAllProducts(){
        if($this->databaseConnection()){
            $stmt = $this->db_connection->prepare("SELECT * FROM products ORDER BY product_id DESC");
            $stmt->execute();
            $result = $stmt->fetch(\PDO::FETCH_ASSOC);
            $this->formatResults($stmt);
        }
    }

这是有效的原始功能,(除了错过第一行)。 我还尝试只定位一行以查看它是否有所作为,但没有返回任何内容。

public function getAllProducts(){
        if($this->databaseConnection()){
            $stmt = $this->db_connection->prepare("SELECT * FROM products WHERE product_id = ? ORDER BY product_id ASC");
            $a =1;
            $stmt->bindParam(1,$a,\PDO::PARAM_INT);
            $stmt->execute();
            while($row = $stmt->fetch(\PDO::FETCH_ASSOC)){
                echo $row['product_id'].'<br/>';
            }
        }
    }

我不确定在这里做什么,该功能似乎可以工作。

【问题讨论】:

  • 你为什么要在PDO::FETCH_ASSOC前面加一个反斜杠?
  • 不知道,如果我不知道会抛出错误“致命错误:类 'classLib\products\PDO'”

标签: php mysql pdo mysqli fetch


【解决方案1】:

因为您正在获取/丢弃一行:

$result = $stmt->fetch(\PDO::FETCH_ASSOC);  // fetch first row
$this->formatResults($stmt);                // fetch all the other rows

只需消除“获取第一行”行。

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 2015-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多