0

I'm writing simple DB connection and when I'm testing it it is not working. What I'm doing wrong? File database:

require_once("config.php");

class MySqlDatabase{
    private $connection;

    function __construct(){
        $this->open_connection();
    }
    public function open_connection(){
        $connection = mysqli_connect(DB_SERVER , DB_USER , DB_PASS , DB_NAME);
        if(!$connection){
            die("Database connection failed:" . mysqli_error($connection));
        }
    }
    public function query($sql){
        $result = mysqli_query($this->connection , $sql);
        $this->confirm_query($result);
        return $result;
    }
   private function confirm_query($result){
        if(!$result){
            die("Database query failed: ".mysqli_error($this->connection));
        }
    }
}

$database = new MySqlDatabase();
$db =& $database;

Than I'm making request :

if(isset ($database)) {echo"true";}else {echo "false";}

$sql ="INSERT INTO users (id, username, password, first_name, last_name)";
$sql .="VALUES (1,'olegsavchuk12','1111','Oleg','Savchuk')";
$result = $database->query($sql);
$sql = "SELECT * FROM users WHERE id=1";
$result_set = $database->query($sql);
$found_user = mysqli_fetch_all($result_set);
echo $found_user['username'];

And see this Warning.

1 Answers1

-1

Your code is Clean except for the omission of 7 simple characters: $this-> Now, let's repost your code, only this time adding $this->:

    <?php
        require_once("config.php");

        class MySqlDatabase{
            private $connection;

            function __construct(){
                $this->open_connection();
            }
            public function open_connection(){
                // THIS SHOULD READ $this->connection NOT $connection
                // YOU ARE IN A CLASS REMEMBER ;-)
                $this->connection = mysqli_connect(DB_SERVER , DB_USER , DB_PASS , DB_NAME);
                // HERE HAS ALSO THE SAME ISSUE AS ABOVE
                if(!$this->connection){
                    // AND EVEN HERE TOO::
                    die("Database connection failed:" . mysqli_error($this->connection));
                }
            }
            public function query($sql){
                // INCIDENTALLY; YOU DID IT PERFECTLY HERE!!! ;-)
                $result = mysqli_query($this->connection , $sql);
                $this->confirm_query($result);
                return $result;
            }
            private function confirm_query($result){
                if(!$result){
                    die("Database query failed: ".mysqli_error($this->connection));
                }
            }
        }

        $database = new MySqlDatabase();
        $db =& $database;
Poiz
  • 7,611
  • 2
  • 15
  • 17