php - 我正在尝试设置类,但在第 41 行不断收到错误 "num_rows line"错误是 "Trying to get property of non-object in line 41"

标签 php html mysql

<?
class Db {
  private $connection;
  public  function __construct($option = null){
    if  ($option != null){
      $host  = $option['host'];
      $user  = $option['user'];
      $pass  = $option['pass'];
      $name  = $option['name'];

    }else {

      global $config;
      $host = $config['db']['host'];
      $user = $config['db']['user'];
      $pass = $config['db']['pass'];
 $name = $config['db']['name'];
 }
    $this->connection = new mysqli($host, $user, $pass, $name);
    if ($this->connection()->connect_error){
      echo("Connection failed: " .$this->connection->connect_error);
      exit;
    }

    $this->connection->query("SET NAMES ''utf8");
  }
  public function first($sql) {
   $records = $this->query($sql);
    if ($records == null){
      return null;
    }
    return $records[0];
  }

  public function  query($sql){
    $result = $this->connection->query($sql);
    $records = array();

     if ($result->num_rows == 0) {
        return null;
      }
      while ($row = $result->fetch_assoc()) {
        $records[] = $row;
      }
    return $records;
  }
  public function connection(){
    return $this->connection;
  }
  public function close(){
    $this->connection()->close();
  }
}

最佳答案

mysqli::query的返回类型功能是混合的,因此它取决于 $sql您正在发送的查询。

如果查询类似于 "CREATE TABLE myTable like anotherTable;"查询的返回结果是 TRUEFALSE 。另一方面,如果它确实是 SELECT查询,如果操作不成功,您应该期待 FALSE否则你有一个 $result对象。

所以最好检查 $result 的类型在执行操作之前。我建议在您的代码中添加一些检查,如下所示:

public function  query($sql){
    $result = $this->connection->query($sql);
    $records = array();
    if($result === FALSE)
       return FALSE;

    if ($result->num_rows == 0) {
       return null;
    ....
}

关于php - 我正在尝试设置类,但在第 41 行不断收到错误 "num_rows line"错误是 "Trying to get property of non-object in line 41",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331878/

相关文章:

php - 这种形式安全吗?

javascript - 如何更改下拉 block 的位置?

php - 单个 php 网站页面内的多个数据库

php - 获取符合特定范围条件的可能组合(大小为 N)

php - 在 PHP 中使用 FPDF 将两个 MultiCell 并排放置

解析模板以发送电子邮件时不解析 Html

php - 如何添加到数据库中的数组并取回每个数组并显示它

java - 如何使用注释保存将列表作为值的 map ?

Mysql select If else if 查询三个值

javascript - jQuery 中的多个同时 Ajax 请求(带有一个回调)