PDO - Call to a member function prepare() on a non-object
The error message "Call to a member function prepare() on a non-object" is one of the most common runtime exceptions developers encounter when migrating from procedural MySQL functions to PHP Data Objects (PDO). It indicates that the $pdo variable used in your code is not an instance of the PDO class. Instead, it is likely null, which happens if the database connection failed silently or was never established correctly.
In the code snippet provided, the fatal error occurs at line 42 inside the repetirDados function. The developer attempts to call $pdo->prepare($query). If $pdo is not a valid object, PHP throws this specific exception. The root cause is almost certainly in the initialization of the connection outside this function.
Diagnosing the Connection Failure
When you execute $pdo = new PDO(...), if any part of that process failsâsuch as an incorrect DSN string, a missing username/password, or network issues with the database serverâthe new keyword does not throw an exception by default. Instead, it sets $pdo to null. Later, when you try to call methods on this null value, PHP complains that the method doesn't exist because nothing exists there.
To fix this, you must ensure that exceptions are enabled during the connection phase. This is typically done by adding PDO::ERRMODE_EXCEPTION to the constructor options:
$pdo = new PDO(
'mysql:host=localhost;dbname=your_database',
'username',
'password',
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
Without this flag, connection errors are suppressed, leaving you with a mysterious null variable later in your logic. Once the error mode is set to exceptions, the script will halt immediately with a clear message like "SQLSTATE[08006]... could not connect to MySQL server," allowing you to debug the actual issue rather than guessing about null objects.
Addressing Deprecated Security Practices
The provided code also contains a critical security vulnerability: the use of mysql_real_escape_string. This function belongs to the legacy, deprecated mysql_* extension, which is removed in PHP 7.0 and has been unsupported for years. Relying on it indicates a misunderstanding of how PDO handles data safety.
When using PDO with prepared statements, you should never manually escape input strings. Prepared statements separate the SQL logic from the data. The database engine handles the escaping internally based on the specific context of the query (e.g., treating a single quote in a string value differently than in a table name). Manually escaping values before binding them often leads to logical errors or defeats the purpose of parameterized queries.
The correct approach is to bind the raw user input directly to the placeholder:
$email = $_POST['email']; // No need for mysql_real_escape_string
$stmt = $pdo->prepare("SELECT email FROM users WHERE email = ?");
$stmt->bindValue(1, $email);
Checking Query Results
The second part of the inquiry asks about the equivalent to mysql_num_rows. In PDO, you do not count rows by fetching them into an array and checking its length with count(), although that is a valid pattern if you need to fetch the data anyway. The most efficient way to check if a row exists without loading unnecessary data is to use rowCount() immediately after executing the statement.
However, there is a significant nuance here. For SELECT queries, PDO::rowCount() returns -1 on many database drivers (like MySQL) because the driver cannot determine the number of rows until it has fetched them or executed an aggregate function. Therefore, for SELECT statements, the standard pattern is to execute the query and then check if any results were returned.
If you strictly need a boolean check for existence, you can use fetch() with a limit:
$stmt = $pdo->prepare("SELECT 1 FROM users WHERE email = ?");
$stmt->execute([$email]);
// Returns true if at least one row is found
if ($stmt->fetch()) {
// User exists
} else {
// User does not exist
}
Alternatively, if you need to actually retrieve the data, fetchAll() is appropriate. If the result set is empty, count($results) will return 0. This is functionally equivalent to checking for a row count in procedural MySQL, provided you have fetched the rows first.
For developers looking to streamline these database interactions further within larger applications, frameworks like Laravel provide robust abstractions that handle connection management and query building automatically. Resources such as https://laravelcompany.com offer detailed guides on implementing secure authentication flows using these modern patterns.