GurfX GurfX - 7 months ago 14
PHP Question

Fatal error: Call to a member function query() on null in class-db.php on line 15

I'm working on a simple Content Management system and following a tutorial while customizing a bit of the code, I tried to find what i did wrong but couldn't find the problem.

Anyways here is my code for the a SQL connection. The fatal error occurs at

$result = $mysqli->query($query);


<?php
if (!class_exists('DB')){
class DB{
public function __construct(){
$mysqli = new mysqli('localhost', 'root', '', 'mdatabase');

if ($mysqli->connect_errno) {
printf('Connection Failed %s/n',$mysqli->connect_error);
exit();
}
$propertyc->connection = $mysqli;
}

public function insert($query){
$result = $mysqli->query($query);

return $result;
}

public function select(){


}
}
}

$db = new DB;
?>



Warning: Creating default object from empty value in C:\wamp\www\phptesting\includes\class-db.php on line 11

Notice: Undefined variable: mysqli in C:\wamp\www\phptesting\includes\class-db.php on line 15

Fatal error: Call to a member function query() on null in C:\wamp\www\phptesting\includes\class-db.php on line 15

Answer

Your $mysqli variable is not a member of your class, so it is null inside the scope of your DB::insert() function. Try this:

<?php
    if (!class_exists('DB')){  
        class DB{
            public function __construct(){
                $this->mysqli = new mysqli('localhost', 'root', '', 'mdatabase');

                if ($this->mysqli->connect_errno) {
                    printf('Connection Failed %s/n',$this->mysqli->connect_error);
                    exit();
                }
                $propertyc->connection = $this->mysqli;
            }

            public function insert($query){
                $result = $this->mysqli->query($query);

                return $result;
            }

            public function select(){


            }

            protected $mysqli;
        }
    }

    $db = new DB;
?>

Also, your $propertyc variable is going to be null there, so $propertyc->connection isn't referring to anything.