Home  >  Article  >  Backend Development  >  Why Am I Getting "Call to a member function prepare() on a non-object" Error in My PDO Code?

Why Am I Getting "Call to a member function prepare() on a non-object" Error in My PDO Code?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-12 08:54:02673browse

Why Am I Getting

PDO Error in Prepare Function Execution

The provided code attempts to prepare a SQL query using PDO, but encounters the error "Call to a member function prepare() on a non-object." This error indicates that the $pdo object is not initialized or accessible within the repetirDados function.

Possible Cause

The most likely cause of this error is that the $pdo object is not defined within the function. It should be either passed as an argument or declared globally and made accessible within the function.

Solution

To resolve the issue, follow these steps:

  1. Initialize $pdo: Ensure that the $pdo object is initialized before calling the prepare function. Alternatively, make $pdo a global variable by adding global $pdo; at the beginning of the function.
  2. Example:

    function repetirDados($email, $pdo) { // Pass $pdo as an argument
        // ... (rest of the code)
    }

Equivalent to mysql_num_rows

For PDO, the equivalent of mysql_num_rows is rowCount. This returns the number of rows affected by the last SQL statement.

$rowCount = $stmt->rowCount();

The above is the detailed content of Why Am I Getting "Call to a member function prepare() on a non-object" Error in My PDO Code?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn