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?
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:
Use the Global Keyword:
function selectInfo($limit, $offset){ global $DBH; $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
Pass the Connection as a Parameter:
function selectInfo(MySQLi $DBH, $limit, $offset){ $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?");
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 ?,?");
}
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 ?,?"); }
Use a Pre-Built Library or Framework:
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!