You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDO(OOP)查询数据库报错:调用rowCount()于布尔值,求排查

Hey there! Let's break down the issues in your code step by step to fix that error:

1. Incorrect placeholder formatting in SQL

You wrapped the :id placeholder in single quotes in your SQL statement. This tells PDO to treat :id as a literal string instead of a parameter to bind values to, which breaks the prepared statement functionality. Remove the single quotes around the placeholder:

$sql = "SELECT * FROM emps WHERE id = :id";

2. Calling rowCount() on a boolean value

The $stmt->execute() method returns a boolean (true on success, false on failure) — not a statement object. You can't call rowCount() on a boolean. Instead, check if execute() succeeded first, then call rowCount() directly on the $stmt object:

Fixed full code

public function selectOne($id) { 
    $sql = "SELECT * FROM emps WHERE id = :id"; 
    $stmt = $this->connect()->prepare($sql); 
    $stmt->bindValue(":id", $id); 
    $stmtExec = $stmt->execute(); 
    
    // First check if execution succeeded
    if ($stmtExec) {
        // Now call rowCount() on the statement object
        if ($stmt->rowCount() > 0) { 
            echo "got results"; 
        } else { 
            echo 'nothing'; 
        }
    } else {
        // Optional: Add error debugging for development
        echo "Query failed: ";
        print_r($stmt->errorInfo());
    }
}

A small extra tip

For single-row queries like this, it's often more intuitive to fetch the result directly and check if it exists, instead of using rowCount():

public function selectOne($id) { 
    $sql = "SELECT * FROM emps WHERE id = :id"; 
    $stmt = $this->connect()->prepare($sql); 
    $stmt->bindValue(":id", $id); 
    
    if ($stmt->execute()) {
        $employee = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($employee) { 
            echo "got results";
            // You can access employee data like $employee['name'] here
        } else { 
            echo 'nothing'; 
        }
    } else {
        echo "Query failed: ";
        print_r($stmt->errorInfo());
    }
}

内容的提问来源于stack exchange,提问作者Rakesh Kohali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:55:04