dsgdfg30210
2016-12-16 05:14
浏览 33
已采纳

PHP数组转换为字符串

So I made a query which returns many restaurants and I put them in a variable $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);

When I try to run my code, it prints Array to string conversion.

The problem appears in this line:

$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";

I searched about the error and I understand but I tried many resolutions and didn't solved the problem.

can someone help please?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • douwu8524 2016-12-16 05:32
    已采纳

    You should do like the following

     $stmt->execute();
     $stmt->bind_result($idRestaurant);
     $stmt->fetch();
    

    Try For PDO:

    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    $idRestaurant = $result['idRestaurant'];
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongsi5381 2016-12-16 05:17

    Check this:

    $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
    

    To do this:

    $rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;
    
    评论
    解决 无用
    打赏 举报
  • doulierong0334 2016-12-16 05:19

    The problem is in this statement

    $idRestaurant = $stmt->fetch();
    

    Have you tried $idRestaurant = $stmt->fetch()[0];?

    You can actually check what's coming into $idResturant by checking it via var_dump

    var_dump($idResturant)
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题