所以我做了一个返回许多餐馆的查询,并将它们放在变量$ row中:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
当我尝试运行我的代码时,它会将Array打印到字符串转换。
问题出现在这一行:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
我搜索了错误并且我理解但是我尝试了许多解决方案而没有解决问题。
有人可以帮忙吗?
答案 0 :(得分:0)
检查一下:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
要做到这一点:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
答案 1 :(得分:0)
问题在于本声明
$idRestaurant = $stmt->fetch();
您是否尝试过$idRestaurant = $stmt->fetch()[0];
?
您可以通过$idResturant
var_dump
实际检查内容
var_dump($idResturant)
答案 2 :(得分:0)
您应该执行以下操作
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
试用PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];