从 mysql 转换为 mysqli 并得到致命错误:无法使用 mysqli 类型的对象作为数组



我正在努力将一些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);
}
?>

此行

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

应该是

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

如果您要迁移到 mysqli,您至少应该阅读这些文档。

使用 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 的预准备语句

最新更新