-2

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

1 Answer 1

1

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.

1
  • Thanks, It worked. I removed the $propertyc->connection entirely. I realised it was useless there.
    – mateos
    Apr 24, 2016 at 2:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.