为foreach()搜索结果提供的参数无效

时间:2018-05-07 11:54:06

标签: php html mysql pdo

我正在尝试在我的Web应用程序中实现过滤系统,用户可以按类别过滤其项目列表。但是,正在显示以下错误消息

"Invalid argument supplied for foreach() in foreach ($item as $key => $val)" 

我不完全确定为什么。我已经尝试了各种方法来克服这个问题,例如尝试将$items设置为数组,但它仍然没有成功。如果不实现搜索系统,则会正确显示特定用户的项目,但是一旦实现过滤器,就会显示上面的错误消息。任何建议将不胜感激。

items.php

<div class="card">
    <div class="card-header">Items</div>
        <form action="" method="post">
            <div class="form-group">
                <label for="name">Search for Items</label>
                    <input type="text" class="form-control" id="search" name="search">
            </div>
            <button type="submit">Search</button>
        </form>
        <div class="card-body items">
           <table class = "items">

           <?php
           $itemsObject = new items($database); 
           $item = $itemsObject->getItemsForUser($_SESSION['userData']['userid'], $_POST['search']); 
           foreach ($item as $key => $val) { 
              echo '<tr><td>'.$val['cat_name'].'</td><td>'.$val['amount'].'</td></tr>';   
      }
?>
           </table>
       </div>
   </div>
</div>

items.classes.php

   public function getItemsForUser($userid, $search = null){
      if(!isset($search)){
        $query = "SELECT i.*, c.cat_name, c.cat_id FROM items AS i INNER JOIN categories AS c ON i.cat_id = c.cat_id WHERE userid = :userid";
        $pdo = $this->db->prepare($query);
        $pdo->bindParam(':userid', $userid);
        } else {
                $query = "SELECT i.*, c.cat_name, c.cat_id FROM items AS i INNER JOIN categories AS c ON i.cat_id = c.cat_id WHERE userid = :userid AND c.cat_name LIKE :search";
            $pdo = $this->db->prepare($query);
            $pdo->bindParam(':userid', $userid);
            $pdo->bindParam(':search', $search);
        }
       $pdo->execute();
       return $pdo->fetchAll();
    }

1 个答案:

答案 0 :(得分:1)

将执行查询放在if / else

之外
if(isset($search)){
    $search = '%'.$search.'%';
    $query = "SELECT i.*, c.cat_name, c.cat_id FROM items AS i INNER JOIN categories AS c ON i.cat_id = c.cat_id WHERE userid = :userid AND c.cat_name LIKE :search";
    $pdo = $this->db->prepare($query);
    $pdo->bindParam(':userid', $userid);
    $pdo->bindParam(':search', $search);
} else {
        $query = "SELECT i.*, c.cat_name, c.cat_id FROM items AS i INNER JOIN categories AS c ON i.cat_id = c.cat_id WHERE userid = :userid";
        $pdo = $this->db->prepare($query);
        $pdo->bindParam(':userid', $userid);
}

$pdo->execute(); // <---- HERE
return $pdo->fetchAll();