Keo Keo - 6 months ago 17
PHP Question

how to solve oop error

I'm newbie here. I tried to solve this for a day and searching all the way but I still couldn't. Please help me.

The error shown up


Notice: Undefined variable: db (in dbFunction)

Fatal error: Call to a member function query() on a non-object (in dbFunction)


and code is

dbConnect.php



class dbConnect{

public $db;

public function __construct(){
$db = new mysqli("localhost", "root", "", "onlineshopping");
$db->set_charset("charset");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
}
}


dbFunction



class dbFunction extends dbConnect {

function __construct() {

}

public $db;

public function UserRegister($fname, $lname, $tel, $email, $pass){
$pass = md5($pass);
$db->query("INSERT INTO member(fname, lname, tel, email, password) values('".$fname."','".$lname."','".$tel."','".$email."','".$pass."')") or die(mysqli_error());
return $db;
}
}

Answer

First of all, your $db is a local variable in the __construct() method and not a class property and second, as pointed by @wogsland it gets overwritten by the child.
You might want to review a bit the OO basics

dbConnect.php

class dbConnect{

    public $db;

    public function __construct(){
        $this->db = new mysqli("localhost", "root", "", "onlineshopping");
        $this->db->set_charset("charset");
        if (mysqli_connect_errno()) {
            printf("Connect failed: %s\n", mysqli_connect_error());
            exit();
        }
    }   
}

dbFunction

class dbFunction extends dbConnect {  

    public function UserRegister($fname, $lname, $tel, $email, $pass){
        $pass = md5($pass);  
        $this->db->query("INSERT INTO member(fname, lname, tel, email, password) values('".$fname."','".$lname."','".$tel."','".$email."','".$pass."')") or die(mysqli_error());  
        return $db;     
    }  
}

Notice the replacement of $db with $this->db in both methods.

Comments