AppTeck
AppTeck

Reputation: 47

Warning: mysqli_query() expects parameter 1 to be mysqli, null given. when i try to connect my DB as an OOP Object

I have this Question about connecting my DB to my php and fetch the data. the error is Warning:

mysqli_query() expects parameter 1 to be mysqli, null given

This is my 2 files the class and the implementation

my code:

<?php

class DB{
    //this is my protected data
    protected $db_hostname = 'localhost';
    protected $db_username = 'root';
    protected $db_password = '';
    protected $db_name = 'blog';

    public function connect(){
        //connection to DB
        $connect_db = mysqli_connect($this->db_hostname, $this->db_username, $this->db_password, $this->db_name) or die(mysqli_connect_error($connect_db));
        //close the connection
        mysqli_close($connect_db);
        //for test
        echo "Greate";
    }
}
?>

Second file:-

$connection  = $db->connect();
$result = "SELECT * FROM blog_posts ";
$query = mysqli_query($connection, $result) or die(mysqli_error());

//loop through my data 
while($row = mysqli_fetch_array($query)){

  ?>
  <div class="well">
    //print data
    By: <?php echo $row->author ?>
    <p><?php echo $row->title ?></p>
  </div>
  <?php } ?>


?>

Upvotes: 0

Views: 611

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

the function need to be like below:-

public function connect(){
   //connection to DB
   $connect_db = mysqli_connect($this->db_hostname, $this->db_username, $this->db_password, $this->db_name);
   if(mysqli_connect_error()){ // you can use mysqli_connect_errorno() also
       die(mysqli_connect_error()); // remove $connect_db
   }else{
     return $connect_db; // return connection object
   }

}

Also changed like below:-

while($row = mysqli_fetch_assoc($query)){

  ?>
  <div class="well">
    //print data
    By: <?php echo $row['author']; ?>
    <p><?php echo $row['title']; ?></p>
  </div>
  <?php } ?>


?>

Note:- mysqli_fetch_array() will give you both indexed+associative array. While mysqli_fetch_assoc() will give you only associative array, which make your resultant array more lighter.Thanks

Look to it for better error reporting:- http://php.net/manual/en/mysqli-driver.report-mode.php

Upvotes: 1

Related Questions