I'm new in oop and I would like to get access to class db in user_access class. But I can't, I get an error and I can't figure out why do I get errors like that:
Warning: mysqli_query() expects parameter 1 to be mysqli, object given in C:\xampp\htdocs\brothers.traning\profiadmin\models\login_Class.php on line 20
Notice: Trying to get property of non-object in C:\xampp\htdocs\brothers.traning\profiadmin\models\login_Class.php on line 21
not
This is my database class:
class db
{
public function db()
{
$db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if (mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
}
And this im my user_access class:
class user_access{
public function __construct($db){
$this->db = $db;
}
public function check_login($login,$password){
$password = sha1($password);
$sql = "SELECT * FROM admins WHERE username = '$login' AND password = '$password'";
$result = mysqli_query($this->db,$sql);
if($result->num_rows > 1){
echo 'ok';
}else{
echo "not";
}
}
}
Now when I use:
$db = new db();
$userDB = new user_access($db);
$userDB->check_login('artur','ol');
I get an error... Can anybody help me, and tell me what is wrong with this code..?
EDIT3: change
$result = mysqli_query($this->db,$sql);
to
$result = $this->db->query($sql);
Look into the manual: http://php.net/manual/en/mysqli.query.php
You are working in object-oriented style so methods of making queries are a little bit different. In the first line you've used procedural-style and it was wrong.
EDIT2: You must return the connection object!
class db
{
public function db()
{
$db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if ($db->connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
else { return $db; }
}
}
And now change the way you call it:
$userDB = new user_access($db->db());
EDIT:
class user_access{
public $db;
public function __construct($db){
$this->db = $db;
}
public function check_login($login,$password){
$password = sha1($password);
$sql = "SELECT * FROM admins WHERE username = '$login' AND password = '$password'";
$result = mysqli_query($this->db,$sql);
if($result->num_rows > 1){
echo 'ok';
}else{
echo "not";
}
}
}
Question: in your user_access class:
public function __construct($db){
$this->db = $db;
}
Where is your $db variable that you want to access by $this->db.