Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array

Converting from mysql to mysqli and getting Fatal error: Cannot use object of type mysqli as array

我正在努力将一些 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 类型的对象作为数组 错误正在这一行被调用:

$运行 = 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);
}

?>

这一行

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

应该是

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

如果你要迁移到 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 的准备好的语句