Home  >  Article  >  Backend Development  >  Why Does \'Call to a Member Function prepare() on a Non-Object\' Occur in PHP, and How Can I Fix It?

Why Does \'Call to a Member Function prepare() on a Non-Object\' Occur in PHP, and How Can I Fix It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 02:27:10412browse

Why Does

Call to Member Function prepare() on a Non-Object: PHP Help

Issue:

The error "Call to a member function prepare() on a non-object" occurs when attempting to call a method on an object that does not exist.

Cause:

The code snippet provided initializes the $DBH variable as a new MySQLi connection object, but fails to pass it as a parameter or declare it as a global variable within the selectInfo() function. As a result, the function cannot access the object and the error is thrown.

Solution:

To resolve this issue, consider the following options:

  1. Use the Global Keyword:

    • function selectInfo($limit, $offset){
        global $DBH;
        $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
  2. Pass the Connection as a Parameter:

    • function selectInfo(MySQLi $DBH, $limit, $offset){
        $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
  3. Create a Function to Get the Database Connection:

    • function getDBH(){
        static $DBH = null;
        if (is_null($DBH)) {
            $DBH = new mysqli(...);
        }
        return $DBH;
      }

    function selectInfo($limit, $offset){

    $DBH = getDBH();
    $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");

    }

  4. Create a Database Wrapper Class:

    • class Database {
        private $conn;
      
        public function __construct(){
            $this->conn = new mysqli(...);
        }
      
        public function selectInfo($limit, $offset){
            $stmt = $this->conn->prepare("SELECT * FROM information LIMIT ?,?");
        }
  5. Use a Pre-Built Library or Framework:

    • Consider using a library or framework that handles database access, such as Doctrine ORM, ADODB, or a full-fledged framework like Zend.

The above is the detailed content of Why Does \'Call to a Member Function prepare() on a Non-Object\' Occur in PHP, and How Can I Fix It?. 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