所以我希望能够从数组中获取值并在SQL查询中使用它,并从这些行中获取信息。我目前的代码是这样的:
$config['exclude_devices'] = array('1','5');
$exclude = $config['exclude_devices'];
foreach ($exclude as $excluded) {
$deviceinformation = mysqli_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
}
while ($row = mysqli_fetch_assoc($deviceinformation)) {
// do stuff here
// write to a variable for use in a table
}
然而,这给出了设备1,2,3,4的输出。
如果我移动foreach
以包含while
,则会产生2,3,4,5,1,2,3,4:
$exclude = $config['exclude_devices'];
foreach ($exclude as $excluded) {
$deviceinformation = mysqli_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
while ($row = mysqli_fetch_assoc($deviceinformation)) {
// do stuff here
}
}
如何修改此代码以仅生成配置中未列出的设备?
答案 0 :(得分:6)
在示例1中:
你跑:
SELECT * FROM `devices` WHERE `device_id` NOT IN(3)
然后
SELECT * FROM `devices` WHERE `device_id` NOT IN(5)
然后,您只需获取第二个查询结果,这样您就可以获取非id为5的设备。
我会使用implode
,因此您排除了您不想要的所有ID。
$excluded = implode(',', $config['exclude_devices']);
$deviceinformation = mysqli_query($db, "SELECT * FROM `devices` WHERE `device_id` NOT IN(" . $excluded . ")");
while ($row = mysqli_fetch_assoc($deviceinformation)) {
// do stuff here
}
演示:https://eval.in/536862
SQL演示:http://sqlfiddle.com/#!9/e4ed47/2