I am attempting to implement a filtering system in my web application, whereby users can filter their list of items by category. However, the following error message is being displayed
"Invalid argument supplied for foreach() in foreach ($item as $key => $val)"
and I'm not entirely certain why. I've tried various approaches to overcome this issue such as trying to set $items
as an array, but it's still not successful. Without implementing the search system, the items for the specific user are correctly displayed, however as soon as I implement the filter, the error message above is displayed. Any advice would be greatly appreciated.
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();
}