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

Chi*_*dak 20 php mysqli

我收到错误:

Object of class mysqli_result could not be converted to string

这是我的代码:

$username2 = htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8');

$con = mysqli_connect('localhost','root','','test');

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

echo "my result <a href='data/$result.php'>My account</a>";
Run Code Online (Sandbox Code Playgroud)

Sha*_*ran 39

mysqli_query()返回一个对象的资源到你的$result变量,而不是一个字符串.

您需要将其循环然后访问记录.你不能直接使用它作为你的$result变量.

代码...

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

  • 你也可以做 if ($row = $result-&gt;fetch_assoc()) {...} 而不是 while,如果你知道它只有 1 行。 (7认同)

Cha*_*wal 5

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

像这样:

$row = mysql_fetch_array($result);
Run Code Online (Sandbox Code Playgroud)

$row根据需要使用数组。

  • 他们在这里使用mysqli_作为API。MySQL_不能与之混用。 (2认同)

Dha*_*man 5

mysqli:query()返回一个mysqli_result对象,该对象无法序列化为字符串。

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

如果您需要单个值。

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

$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;
Run Code Online (Sandbox Code Playgroud)

如果您需要多个值。

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

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

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