我有这些数据库,其中保存了一些活动。它们就是这样相互联系的。
ACTIVITIES WEEKDAYS DAYPARTS
id id id
title weekday daypart
daypart_id
weekday_id
对于过滤器按钮,我想过滤工作日的活动。因此,例如,他们单击星期一,就可以获取星期一的所有活动。
问题在于,一列可以获取多个参数,例如,它们可以单击“星期一”,但也可以单击“星期二”和“星期三”。
我尝试使用以下代码进行操作:
public function selectAllActivities($dayparts = false, $weekdays = false){
$sql = "SELECT `activities`.*, `dayparts`.`daypart`, `weekdays`.`weekday`
FROM `activities`
INNER JOIN `dayparts` ON `dayparts`.`id` = `activities`.`daypart_id`
INNER JOIN `weekdays` ON `weekdays`.`id` = `activities`.`weekday_id`";
if (!empty($dayparts)) {
$placeHolders = [];
foreach ($dayparts as $key => $daypart) {
$placeHolders[$key] = ':daypart_id'.$key;
}
$sql .= ' AND `daypart` IN ('.implode(', ',$placeHolders).')';
}
if (!empty($weekdays)) {
$placeHolders = [];
foreach ($weekdays as $key => $weekday) {
$placeHoldersB[$key] = ':weekday_id'.$key;
}
$sql .= ' AND `weekday` IN ('.implode(', ',$placeHoldersB).')';
}
$stmt = $this->pdo->prepare($sql);
if ($dayparts) {
foreach ($dayparts as $key => $daypart) {
$stmt->bindValue($placeHolders[$key], $daypart);
}
}
if ($weekdays) {
foreach ($weekdays as $key => $weekday) {
$stmt->bindValue($placeHoldersB[$key], $weekday);
}
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
当我尝试过滤时,出现以下错误:
Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/INT2_DEV/dao/ActivityDAO.php on line 15
foreach函数有问题,但是我真的不知道是什么。
答案 0 :(得分:0)
为...中的foreach()提供了无效的参数
发生此错误是因为foreach
试图迭代的变量不是数组。
根据您的逻辑,$dayparts
或$weekdays
都不为空(即!empty($dayparts)
为真,而$dayparts
也为真。
我建议在使用变量之前先使用is_array($x)
测试变量是否为数组:
if (is_array($dayparts)) {
...
}