Fatal error: Uncaught Error: Call to a member function rowCount() on bool

created at 06-06-2022 views: 18

problem

When writing a php job, there is a query statement in it

<?php
session_start();
// .Connect to the database
try {
     $pdo = new PDO("mysql:host=localhost;dbname=test;", "root", "root");
} catch (PDOException $e) {
     die("Database connection failed". $e->getMessage());
}
// .Prevent Chinese garbled characters
$pdo->query("SET NAMES 'UTF8'"); // . Splice sql statements to get information
$sql = "SELECT * FROM stu WHERE name = ".$_SESSION['name'];

$stmt = $pdo->query($sql);//Return the preprocessing object
if ($stmt->rowCount() > 0) {
     $stu = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>

On the surface, there is no problem

but the error is

Fatal error: Uncaught Error: Call to a member function rowCount() on bool in D:\Apache24\htdocs\ex02c.php:21 Stack trace: #0 {main} thrown in D:\Apache24\htdocs\ex02c.php on line 21

solution

rowCount() needs to return an object, but now there may be an error, returning a boolean, the method of the object cannot be called rowCount()

The reason for returning a boolean is likely to be on the sql statement or the connection to the database

In the above code, the error is just above the sql statement

$sql = "SELECT * FROM stu WHERE name = ".$_SESSION['name'];

The .$_SESSION['name'] is a string variable called, but in the sql statement, the string variable should be enclosed in ''

So change to

$sql = "SELECT * FROM test2 WHERE name ='{$_SESSION['name']}'";

As for I have used this method before, but no error

<?php
     // .Connect to the database
     try{
         $pdo = new PDO("mysql:host=localhost;dbname=php;","root","123456");
     }catch(PDOException $e){
         die("Database connection failed".$e->getMessage());
     }
     // .Prevent Chinese garbled characters
     $pdo->query("SET NAMES 'UTF8'"); // . Splice sql statements to get information
     $sql = "SELECT * FROM shangpin WHERE id = ".$_GET['id'];
     $stmt = $pdo->query($sql);//Return the preprocessing object
     if( $stmt->rowCount()> 0){
         $stu = $stmt->fetch(PDO::FETCH_ASSOC);//Parse according to associative array
     }else{
         die("No data to modify!");
     }
     ?>

The reason is that the .$_GET['id'] in it is an int type variable, which can be directly spliced in the sql statement, so there is no problem.

created at:06-06-2022
edited at: 06-06-2022: