【问题标题】:PHP Error - Object of class could not be converted to String [duplicate]PHP错误-类的对象无法转换为字符串[重复]
【发布时间】:2015-05-15 09:22:08
【问题描述】:

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

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

这是我的代码(来自articles.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;
?>

【问题讨论】:

  • $max = (string)$max; 不计算。请阅读如何正确处理来自mysqli_query 的结果。

标签: php mysqli


【解决方案1】:

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];

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 2015-02-05
      • 1970-01-01
      • 2014-03-31
      • 2017-07-25
      • 2016-12-02
      • 2016-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多