PHP: Addressing the "Call to a Member Function prepare() on a non-Object" Error
When utilizing prepared statements in PHP, the "Call to a member function prepare() on a non-object" error indicates an incorrect or missing database connection. To resolve this issue, ensure that the database connection is properly created and accessible within the function.
In the example provided, the error occurs because the $DBH variable is not accessible within the selectInfo() function. This is due to variable scoping. To address this, we have several options:
Use the global Keyword:
Pass the Database Connection as a Parameter:
Create a Database Connection Retrieval Function:
Implement a Database Wrapper Class:
Use a Pre-Built Framework or Library:
By employing one of these methods, you can establish a proper connection and resolve the "Call to a member function prepare() on a non-object" error, allowing your prepared statement to execute successfully.
The above is the detailed content of Why Am I Getting the \'Call to a Member Function prepare() on a non-Object\' Error in PHP?. For more information, please follow other related articles on the PHP Chinese website!