So I want to be able to get a value from an array and use it in an SQL query, and get information from those rows. My current code is like so:
$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
}
However, this gives the output of devices 1,2,3,4.
If I move the foreach
to include the while
, it produces 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
}
}
How can I modify this code to produce only the devices that are not listed in the config?
In example 1:
You run:
SELECT * FROM `devices` WHERE `device_id` NOT IN(3)
then
SELECT * FROM `devices` WHERE `device_id` NOT IN(5)
You then only fetch the second queries results so you should get back devices with non 5 for their ids.
I would use an implode
so you exclude all ids you don't want.
$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
}
Demo: https://eval.in/536862
SQL Demo: http://sqlfiddle.com/#!9/e4ed47/2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.