PHP 错误 - 类的对象无法转换为字符串


PHP Error - Object of class could not be converted to String

我在编写文章系统时遇到错误。我想回应最新的文章。如果有更简单的方法可以做到这一点,请告诉我。这是错误:

可捕获的致命错误:无法将第 mysqli_result 类的对象转换为第 5 行/public_html/cms/articles 中的字符串.php

这是我的代码(来自文章.php):

<?php
require 'connect.php';
$getmax = "SELECT id FROM news ORDER BY id LIMIT 1";
$max = mysqli_query($conn, $getmax);
$max = (string)$max;
$sql = "SELECT * FROM news WHERE id=$max";
$result = mysqli_query($conn, $sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    $articleOneTitle = $row["title"];
    $articleOneDesc = $row["description"];
    $articleOneContent = $row["content"];
}
} else {
echo "Sorry! - No articles are currently available, please check back later.";
}
echo $max;
?>

>mysqli_query返回一个mysqli_result对象;不能将其直接强制转换为字符串。 它应该看起来更像这样。

$getmax = "SELECT id FROM news ORDER BY id LIMIT 1";
$result = mysqli_query($conn, $getmax);
$row = $result->fetch_row();
$max = (string)$row[0];

在第 5 行,将mysql_query调用的结果类型转换为字符串。PHP 不喜欢这样,并且正在处理错误。mysqli_query函数将在失败时返回false,或在成功时返回mysqli_result。