警告:mysqli_query()期望参数1为mysqli,给定为null.当我尝试将我的数据库作为OOP对象连接时 [英] Warning: mysqli_query() expects parameter 1 to be mysqli, null given. when i try to connect my DB as an OOP Object

查看:105
本文介绍了警告:mysqli_query()期望参数1为mysqli,给定为null.当我尝试将我的数据库作为OOP对象连接时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有关于将数据库连接到PHP并获取数据的问题.错误是警告:

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

mysqli_query()期望参数1为mysqli,给定为空

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

这是我的2个文件的类和实现

This is my 2 files the class and the implementation

我的代码:

<?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 } ?>


?>

推荐答案

该功能需要如下所示:-

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
   }

}

也进行了如下更改:-

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

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


?>

注意:-mysqli_fetch_array()将同时提供索引和关联数组.虽然mysqli_fetch_assoc()仅会为您提供关联数组,这会使您得到的数组更轻巧.谢谢

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

查看它以获得更好的错误报告:- 查看全文

相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆