【问题标题】:Object of class mysqli_result could not be converted to string类 mysqli_result 的对象无法转换为字符串
【发布时间】:2022-01-05 03:03:06
【问题描述】:

我收到错误:

mysqli_result 类的对象无法转换为字符串

这是我的代码:

$result = mysqli_query($con, "SELECT classtype FROM learn_users WHERE username='abcde'");

echo "my result <a href='data/$result.php'>My account</a>";

【问题讨论】:

标签: php mysqli


【解决方案1】:

在使用$result 变量之前,您应该使用$row = mysqli_fetch_array($result)mysqli_fetch_assoc() 函数。

像这样:

$row = mysqli_fetch_array($result);

并根据需要使用$row 数组。

【讨论】:

  • 他们在这里使用 mysqli_ 作为 API。 MySQL_ 不与它混合。
【解决方案2】:

mysqli:query()返回一个mysqli_result对象,不能序列化成字符串。

您需要从对象中获取结果。以下是操作方法。

如果您需要单个值。

从结果中获取一行,然后访问列索引 0 或使用关联键。如果结果中不存在任何行,请使用 null-coalescing 运算符。

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

如果您需要多个值。

使用foreach 循环遍历结果并逐行获取。您可以使用列名作为数组索引来访问每一列。

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];
}

【讨论】:

    【解决方案3】:

    尝试:

    $row = mysqli_fetch_assoc($result);
    echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
    

    【讨论】:

      【解决方案4】:

      mysqli_query() 方法将对象资源返回到您的 $result 变量,而不是字符串。

      您需要循环它然后访问记录。您只是不能直接将其用作您的 $result 变量。

      while ($row = $result->fetch_assoc()) {
          echo $row['classtype']."<br>";
      }
      

      【讨论】:

      • 如果你知道它只有 1 行,你也可以使用 if ($row = $result->fetch_assoc()) {...} 而不是 while。
      【解决方案5】:

      query() 函数返回一个对象,您需要从该函数返回的内容中获取记录。查看page 上的示例,了解如何从 mysql 打印数据

      【讨论】:

        猜你喜欢
        • 2011-03-16
        • 2014-03-31
        • 2019-03-19
        • 2016-06-17
        • 1970-01-01
        相关资源
        最近更新 更多