Home > Article > Backend Development > Why Am I Getting "Call to Member Function prepare() on a Non-Object" in PDO?
Call to Member Function prepare() on a Non-Object in PDO
This question revolves around an error encountered while using the PDO extension for PHP. The error suggests that the prepare() method was invoked on a non-object.
Possible Cause
The primary cause of this error lies in the undefined $pdo variable. It is essential to ensure that $pdo is properly defined or passed as an argument to the function where the prepare() method is being employed.
Alternative Solution
Alternatively, you can include global $pdo; at the beginning of the function to access the $pdo variable from the global scope. However, this approach is considered less desirable as it doesn't promote code modularity.
Equivalent to mysql_num_rows
Since PHP Data Objects (PDO) is a more advanced database abstraction layer than the now-deprecated MySQLi extension, it doesn't provide a direct equivalent to mysql_num_rows. However, you can obtain the number of rows affected by a query or fetched by a statement using rowCount().
For instance, you can modify your code to retrieve the number of affected rows:
$ok = $stmt->execute(); $rowCount = $stmt->rowCount();
The above is the detailed content of Why Am I Getting "Call to Member Function prepare() on a Non-Object" in PDO?. For more information, please follow other related articles on the PHP Chinese website!