<Fatal error: Call to a member function prepare() on a non-object in G:\\xampp\\htdocs\\live\\Billing Suryas\\model\\DBConfig.php on line 28
You are trying to store the DB connection handle in a variable $conn
. But that is just a local variable, not the class property $conn
. To use the later you have to access it is $this->conn
.
So your connection method should be something like
public function dbConnection()
{
try {
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $exception) {
echo "Connection error: " . $exception->getMessage();
}
}
Given that you now can use $this->conn
in other functions
public function login($usname, $uspswd)
{
try {
$stmt = $this->conn->prepare("select * from users where user_name=:uname and password=:paswrd and permission='0' and delet='0'");
$stmt->execute(array(':uname'=>$usname, ':paswrd'=>$uspswd));
$userRow = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() == 1) {
if(password_verify($uspswd, $userRow['password'])) {
$_SESSION['user_session'] = $userRow['user_id'];
return true;
} else {
return false;
}
}
} catch(PDOException $exception) {
echo $exception->getMessage();
}
}
In other words: using $conn
instead of $this->conn
does not refer to the objects property $conn
, but a local variable $conn
in the methods. But local variables are not persistent. So once you leave the method dbConnection()
and try to reuse that variable by picking the same name in login()
, the identifier $conn
actually refers to two different local variables. Which of course means that it does not hold any value in the login()
method which leads to the error you receive.
There are other approaches to this like "injecting the connection object" into your methods. But the above is a clean and usually preferred approach.
You write a class with these properties:
class Database
{
private $host = "localhost";
private $db_name = "new_suryas1";
private $username = "root";
private $password = "";
public $conn;
Inside a class method, variable scope is same as functions: external variables are not accessible.
To access to class properties inside a class method you have to use $this
:
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
(...)
$stmt = $this->conn->prepare("select * from users where user_name=:uname and password=:paswrd and permission='0' and delet='0'");