【问题标题】:PHP mysqli Fatal error: Call to a member function query() on nullPHP mysqli 致命错误:在 null 上调用成员函数 query()
【发布时间】:2015-08-01 07:03:36
【问题描述】:

我遇到了这个错误,我不知道如何解决。

'Fatal error: Call to a member function query() on null in C:\xampp\htdocs\cms\lib\db.php on line 46'

代码:

class db {

public $mysqli;

function Connect() {

         $server = 'localhost';
        $dbusername = 'root';
        $database = 'cms';
        $dbpassword = 'lopaka';
        $this->mysqli = new mysqli($server, $dbusername, $dbpassword, $database);

        /* connectie bekijken */
        if (mysqli_connect_errno()) {
            printf("Connectie mislukt: %s\n", mysqli_connect_error());
            exit();
        }
    }


function GetGallery() {

    $query = "SELECT * FROM menu";
    $action = $this->mysqli->query($query);

    while ($row = $action->fetch_assoc()) {
        $gallery .= '<a href="'.$siteurl.''.$row['url'].'" title="'.$row['alt'].'" data-gallery="" ><img src="'.$siteurl.''.$row['url'].'" width="75px" height="75px"></a>';    
    }

    return $gallery;
} 

}

谢谢!!!

编辑 - 现在可以使用,但现在我遇到了一些新错误:

注意:未定义索引:第 42 行 C:\xampp\htdocs\cms\lib\db.php 中的 url

注意:未定义索引:第 42 行 C:\xampp\htdocs\cms\lib\db.php 中的 alt

注意:未定义索引:第 42 行 C:\xampp\htdocs\cms\lib\db.php 中的 url

【问题讨论】:

  • 请添加您的用例,在获取图库之前您可能没有调用Connect()方法!
  • $db = new db(); $db->连接(); $db->GetGallery();现在可以,但现在我遇到了新错误
  • while() 循环中插入var_dump($row);die(); 作为第一条语句,然后报告!!

标签: php mysqli fatal-error


【解决方案1】:

你应该在你的类中添加 __construct() 方法... 像这样添加...

public function __construct()
{           
    $this->Connect();
}

这里 Connect() 将被初始化,然后只有 mysqli query() 方法可以工作。

【讨论】:

    【解决方案2】:
         while ($row = mysqli_fetch_assoc($action)) {
                $gallery .= '<a href="'.$siteurl.''.$row['url'].'" title="'.$row['alt'].'" data-gallery="" ><img src="'.$siteurl.''.$row['url'].'" width="75px" height="75px"></a>';    
            }
     return $gallery;
    

    【讨论】:

    • 这是错误的,除了错误发生在之前这个部分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多