This question already has an answer here:
My PHP function is very simple. It's just using prepared statements to query the database, but I can't understand why it's not working.
I keep getting a 'Call to a member function prepare() on a non-object' error, even though I have declared $conn
as a private variable and using $this->conn
<?php
require_once 'constants.php';
class Mysql {
private $conn;
function ___construct(){
$this->conn = new mysqli (DB_SEVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$this->conn){
die('There was a problem connecting to the database!');
}
}
function verify_name_and_pass ($un, $pwd) {
$query = "SELECT * FROM users
WHERE username = ? AND user_password = ?
LIMIT 1";
if ($stmt = $this->conn->prepare($query)) {
$stmt->bind_param('ss', $un, $pwd);
$stmt->execute();
if ($stmt->fetch()) {
$stmt->close();
return true;
}
}
}
}
</div>
The problem is your __construct()
function. There is at least one typo:
__construct()
is spelled with 2 _
, you spelled it with 3.DB_SERVER
instead of DB_SEVER
.Also, once you established that $this->conn
is not null
, you should check that the connection is correctly established by reading $this->conn->connect_errno
and making sure it's 0
.