【问题标题】:mysqli_query() null given errormysqli_query() null 给定错误
【发布时间】:2013-09-26 14:20:54
【问题描述】:

这些代码有什么问题?我对mysqli非常陌生。我总是收到这个错误

警告:mysqli_query() 期望参数 1 为 mysqli,在第 11 行的 C:\localhost\path\core.php 中给出 null 错误,查询失败!!!

我测试了连接并且它正在工作并且连接,所以我不明白为什么我总是看到这个警告并且我的查询失败了。我还检查了查询,它是正确的。这是我的代码:

configuration.php

<?php
$dbhost = 'xxx'; 
$dbuser = 'xxx';
$dbpass = 'xxx'; 
$dbname = 'xxx'; 

$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die ('Error connecting to mysql');

?>

core.php

<?php
require_once('configuration.php');

class Core {
    public $coreTable;
    public $result;
    public $num_rows;

    function Execute($query) {
        $this->result = mysqli_query($conn,$query) or die('Error, query failed!!!'); //line 11
        $this->row_cnt = mysqli_num_rows( $this->result );
    }
}
?>

【问题讨论】:

  • $conn 变量超出范围,因为它不是核心类的一部分。
  • 使用 MySQLi 作为对象,甚至比程序风格更好。 => class CoreDatabase extends \MySQLi { ... };

标签: php mysqli


【解决方案1】:

您可能正在尝试访问 Core 类之外的变量。首先,您可能想在此处阅读有关 variable scope 的信息。

快速而肮脏的解决方案是:

第一次实例化 Core 类时注入 $conn 变量。

在 Core 类中添加一个__construct() {} 方法:

<?php
require_once('configuration.php');

class Core {
    public $connection; // Notice here
    public $coreTable;
    public $result;
    public $num_rows;

    /**
     * Documenting classes and methods is a good practice.
     * Constructor method
     * 
     * @param Resource $conn Mysql connection.
     * @return void
     */
    public function __construct($conn)
    {
       $this->connection = $conn;
    }

    function Execute($query) {
        $this->result = mysqli_query($this->connection,$query) or die('Error, query failed!!!'); //line 11
        $this->row_cnt = mysqli_num_rows( $this->result );
    }
  }
?>

当你第一次实例化你的 Core 类时:

$class = new Core($conn); // We are injecting the $conn here

就是这样。如果您觉得这很有趣,请在此处阅读有关 dependency injection 的更多信息。

【讨论】:

    【解决方案2】:

    这是一个变量范围问题。您的 $conn 变量是在函数范围之外定义的,并且在 Core 类中不可用。

    作为快速修复,您可以将其更改为全局变量:

    global $conn;
    

    有关详细信息,请参阅PHP Manual 文档。

    【讨论】:

    • 哦,对不起,它现在可以工作了,我在 configuration.php 上定义了它,而不是在函数内部执行。我认为 php 与 C 中的相同。谢谢。
    • 为什么要创建一个可以在所有范围内使用的全局,为什么不将它传递给必要的函数呢?还是使用上面发布的其他示例?
    【解决方案3】:

    你当前使用的范围内不存在$conn

    要么在创建时将连接传递给类,要么使用全局变量 $conn

    【讨论】:

      猜你喜欢
      • 2022-01-24
      • 1970-01-01
      • 2016-02-21
      • 1970-01-01
      • 1970-01-01
      • 2016-03-24
      • 1970-01-01
      • 2018-05-04
      • 1970-01-01
      相关资源
      最近更新 更多