php/mysql错误:mysqli\u result类的对象无法转换为字符串

kyxcudwk  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(325)

我刚刚开始学习mysql和php(basics),我已经被这个错误困扰了两天。我有html代码:

<html>
<head>
    <title>Title</title>
</head>
<body>
    <?php include 'pehape.php' ?>
<span>Username:</span><?php echo $var ?>
</body>
</html>

我只是尝试使用以下代码从数据库中获取用户的名称:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

$var = $conn->query("SELECT Name FROM users WHERE ID=0");

?>

这是我在网络浏览器中得到的结果。

Username:
Recoverable fatal error: Object of class mysqli_result could not be converted to string in /storage/ssd3/749/7441749/public_html/index.php on line 7

现在,我得到的结果是object,但我不知道如何使用php将其转换为字符串-有人知道怎么解决这个问题吗?把对象转换成字符串。
我试过使用print\r函数,但没有成功。我发现关于这个的信息很少。另外,如果您需要一些信息,这是我的数据库结构(我想可能会有影响,不知道):http://prntscr.com/l5xu9n

mzillmmw

mzillmmw1#

$var 在代码中实际上是一个类型为 mysqli_result .
这实际上是一个resultset的句柄,您必须使用某种 fetch .

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// dont normally get ID's of zero so I chnaged this to 1
$result = $conn->query("SELECT Name FROM users WHERE ID=1");

// now get the result row
$row = $result->fetch_assoc();     // row will be an array

?>

现在在你的html中你可以这样做了

<html>
<head>
    <title>Title</title>
</head>
<body>
    <?php include 'pehape.php' ?>
<span>Username:</span><?php echo $row['Name'];?>
</body>
</html>
zaqlnxep

zaqlnxep2#

您应该这样获取结果:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

if($result = $conn->query("SELECT Name FROM users WHERE ID=0")) {
    $var = $result->fetch_object();
    $result->close();
}
?>

然后在html中:

<html>
<head>
    <title>Title</title>
</head>
<body>
    <?php include 'pehape.php' ?>
<span>Username:</span><?php echo $var->Name ?>
</body>
</html>

检查文档:http://php.net/manual/pt_br/mysqli-result.fetch-object.php

相关问题