我收到错误:
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)
在使用$result变量之前,应使用$row = mysql_fetch_array($result)或mysqli_fetch_assoc()函数。
像这样:
$row = mysql_fetch_array($result);
Run Code Online (Sandbox Code Playgroud)
并$row根据需要使用数组。
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)