【问题标题】:Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array从 mysql 转换为 mysqli 并出现致命错误:无法使用 mysqli 类型的对象作为数组
【发布时间】:2015-05-12 14:31:20
【问题描述】:

我正在将一些 PHP 代码从 mysql 转换为 mysqli。我创建了一个错误,无法理解如何修复它。任何建议将不胜感激。

代码如下所示:

    <?php
include ("admin/includes/connect.php");

$query = "select * from posts order by 1 DESC LIMIT 0,5";

$run = mysqli_query($conn["___mysqli_ston"], $query);

while ($row=mysqli_fetch_array($run)){

$post_id = $row['post_id'];
$title = $row['post_title'];
$image = $row['post_image'];

?>

产生的错误是:致命错误:不能使用mysqli类型的对象作为数组 该行正在调用错误:

$run = mysqli_query($conn["___mysqli_ston"], $query);

在上面的行中,$conn 是数据库连接文件中的一个变量,它具有以下代码:

<?php

// Stored the db login credentials in separate file.
require("db_info.php");

// Supressing automated warnings which could give out clues to database user name, etc.
mysqli_report(MYSQLI_REPORT_STRICT);

// Try to open a connection to a MySQL server and catch any failure with a controlled error message.
try {

$conn=mysqli_connect ('localhost', $username, $password) or die ("$dberror1");

} catch (Exception $e ) {
     echo "$dberror1";
     //echo "message: " . $e->message;   // Not used for live production site.
     exit;
}

// Try to Set the active MySQL databaseand catch any failure with a controlled error message.
try {

$db_selected = mysqli_select_db($conn, $database) or die ("$dberror2");

} catch (Exception $e ) {
     echo "$dberror2";
     //echo "message: " . $e->message;   // Not used for live production site.
     exit;

     // We want to stop supressing automated warnings after the database connection is completed.
     mysqli_report(MYSQLI_REPORT_OFF);
}

?>

【问题讨论】:

    标签: php arrays mysqli compiler-errors


    【解决方案1】:

    这一行

       $run = mysqli_query($conn["___mysqli_ston"], $query);
    

    应该是

       $run = mysqli_query($conn, $query);
    

    【讨论】:

    • 非常感谢您的解决方案是完美的解决方案!这对我帮助很大,因为同样的问题发生在多个地方。
    【解决方案2】:

    如果您要迁移到 mysqli,您至少应该阅读 these docs

    使用mysqli连接的正确方法:

    <?php
        $mysqli = new mysqli("example.com", "user", "password", "database");
        if ($mysqli->connect_errno) {
            echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
        }
        $res = $mysqli->query("SELECT id FROM test ORDER BY id ASC");
    
        while ($row = $res->fetch_assoc()) {
            echo " id = " . $row['id'] . "\n";
        }
    ?>
    

    您还应该考虑使用 mysqli 的预处理语句

    【讨论】:

    • Mario,感谢您提供这些文档的链接。我一直在 php.net 上查找旧的 sql 语句,然后单击它说这些已弃用的链接,然后点击指向新 mysqli 函数的链接。然后当然要尝试学习它们。感谢您提供关于 db 连接的代码示例。我有些担心这如何在出现错误时回显 db 用户的名称,我不确定这是否有帮助?
    • 这只是一个非常简单的例子。要回显 dbuser,当然欢迎您将值保存在变量中并使用它来调用 new mysqli($host, $user, $password, $database)
    猜你喜欢
    • 2017-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2012-05-29
    相关资源
    最近更新 更多