Anybody help me to find what is wrong with the below code? I have class student.php extends db.php.
Student.php
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
$res = $this->db_connect();
}
}
$result = new Student();
db.php
<?php
abstract class Db {
protected $db_host;
protected $db_user;
protected $db_password;
protected $db_name;
public function __construct() {
$this->db_host = 'localhost';
$this->db_user = 'root';
$this->db_password = '';
$this->db_name = 'student';
}
protected function db_connect() {
if(!isset($GLOBAL['db_connection'])) {
$GLOBAL['db_connection'] = new mysqli($this->db_host, $this->db_user, $this->db_password, $this->db_name);
}
if(mysqli_connect_errno()) {
$responseArray['status'] = '500';
$responseArray['response'] = 'Error'. mysqli_connect_error().' Error No: '. mysqli_connect_errno();
}
else {
$responseArray['status'] = '200';
$responseArray['response'] = 'Database connection success';
}
return $responseArray;
}
}
?>
it returns the result
mysqli::__construct(): (HY000/1045): Access denied for user ''@'localhost' (using password: NO)
I understand DB variables are empty that's why I get the error. but I need to make sure what's wrong with the code.
You have override __construct()
method so default values are not set.
Check this:
<?php
require_once('db.php');
class Student extends Db {
public function __construct() {
// call Db's constructor
parent::__construct();
$res = $this->db_connect();
}
}