Home > Article > Backend Development > Why does my PHP code throw a \'Call to a Member Function prepare() on a Non-Object\' error, and how can I fix it?
Your PHP code triggers an error message indicating that you are attempting to access the prepare() method of an object that doesn't exist. Let's delve into the provided code to identify the source of this error:
$DBH = new mysqli("host", "test", "123456", "dbname"); function selectInfo($limit, $offset) { $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?"); $stmt->bind_param("ii", $limit, $offset); $stmt->execute(); } selectInfo();
The error originates from the scope of the $DBH variable. Within the selectInfo() function, you are trying to access $DBH without specifying its scope. Since $DBH is not defined within the function, it cannot be accessed directly.
To resolve this issue, you have several options:
1. Use the global Keyword:
function selectInfo($limit, $offset) { global $DBH; $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?"); $stmt->bind_param("ii", $limit, $offset); $stmt->execute(); }
2. Pass $DBH as a Function Parameter:
function selectInfo($DBH, $limit, $offset) { $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?"); $stmt->bind_param("ii", $limit, $offset); $stmt->execute(); }
3. Create a Function to Retrieve $DBH:
function getDBH() { static $DBH = null; if (is_null($DBH)) { $DBH = new mysqli("host", "test", "123456", "dbname"); } return $DBH; } function selectInfo($limit, $offset) { $DBH = getDBH(); $stmt = $DBH->prepare("SELECT * FROM information LIMIT ?,?"); $stmt->bind_param("ii", $limit, $offset); $stmt->execute(); }
By implementing one of these options, you will establish the correct scope for $DBH within the selectInfo() function, allowing it to access the necessary database connection.
The above is the detailed content of Why does my PHP code throw a \'Call to a Member Function prepare() on a Non-Object\' error, and how can I fix it?. For more information, please follow other related articles on the PHP Chinese website!