Home > Backend Development > PHP Tutorial > Why Am I Getting 'Call to a Member Function Prepare() on a Non-Object' in My PDO Code?

Why Am I Getting 'Call to a Member Function Prepare() on a Non-Object' in My PDO Code?

Mary-Kate Olsen
Release: 2024-11-19 19:36:03
Original
738 people have browsed it

Why Am I Getting

PDO Call to Member Function Prepare on a Non-Object: Causes and Solutions

When attempting to use the prepare() method of the PDO object, an error can occur: "Call to a member function prepare() on a non-object." This error indicates that the $pdo object is not properly initialized within the function causing the issue.

In the provided code snippet, the repetirDados() function doesn't declare the $pdo object or pass it as a parameter. To resolve this error, you can either:

  • Pass the PDO object as a parameter:
    Modify the function definition to include the $pdo object as an argument, ensuring that it is passed into the function when called.
  • Declare the PDO object globally: (Not recommended)
    You can declare the $pdo object in the global namespace and make it accessible to the function by adding global $pdo; at the beginning of the function. However, this approach is not preferred as it can lead to potential conflicts if other code is accessing the same global variable.

PDO Equivalent of MySQL Functions

You also inquired about the PDO equivalent of MySQL function mysql_num_rows. PDO provides an alternative method called rowCount() which serves the same purpose. It returns the number of affected rows in the result set after executing a query.

In your code, you can use $stmt->rowCount() instead of $results == 0 to check if any rows were returned by the query.

The above is the detailed content of Why Am I Getting 'Call to a Member Function Prepare() on a Non-Object' in My PDO Code?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template