php - MySQL、PHP : Select * from table where id is not in array

标签 php mysql arrays

所以我目前有一个数据库表,我试图在其中选择除我创建的数组中包含的记录之外的所有记录。作为一些背景上下文:

有问题的数据库表的结构是:

server_status:
id int(11)
server_id int(11)
time_checked datetime
status char(1)

我将数据放入散列中的 PHP 脚本如下所示:

$sql2 = "SELECT server_id, time_checked,id from server_status where   time_checked<'$date' order by server_id;";
$result2=$conn->query($sql2);
while($row2 = $result2->fetch_assoc()){

 $server_id = $row2['server_id'];
 $id = $row2['id'];
 $dt = $row2['time_checked'];

 $year = substr($dt,0,4);
 $month = substr($dt,5,2);
 $day = substr($dt,8,2);

 $day = "$year-$month-$day";

 $all[$server_id][$day] = $id;  // ARRAY

}

所以我想做的是创建一个 MySQL 查询,从数组中读取 ID ($id),然后从中选择 * APART。通过查找,我似乎必须使用“where not”子句,但我不知道如何在其中引用哈希。

进一步说明:我现在有一个数组可以提取如下所示的数据:

1{
2016-05-05 : 252
2016-05-10 : 406
2016-04-27 : 141
2016-05-04 : 164
2016-05-09 : 263
2016-05-03 : 153
2016-04-26 : 131
2016-04-14 : 1
2016-04-18 : 31
2016-04-21 : 111
2016-04-20 : 61
2016-04-19 : 51
2016-04-15 : 21
2016-04-25 : 121
}
2{
2016-05-10 : 452
2016-05-05 : 198
2016-05-09 : 264
2016-05-04 : 165
2016-04-26 : 132
2016-04-27 : 143
2016-04-25 : 122
2016-04-21 : 112
2016-05-03 : 154
}

我想从这个数组中获取 ID(例如 154)并选择表中没有上述任何 ID 的所有内容。我希望这有助于澄清?!

任何帮助将不胜感激!

最佳答案

如果 $all 是您要从中提取不需要的 ID 的数组,这可能是您在提供的代码之后所需要的:

$ids_to_exclude = array();

// iterate through servers
foreach ($all as $server_id => $dates) {
    // iterate through dates of each server
    foreach ($dates as $date => $id) {
        // If a value is not in the array, add it.
        // In case ids don't repeat, you won't need this if
        if (!in_array($id, $ids_to_exclude)) {
             // add $id to the array
             $ids_to_exclude[] = $id;
        }
    }
}

$sql_condition = "where `id` not in (".implode(",",$ids_to_exclude).")";

编写带有字符串连接的查询时要小心。了解 SQL Injection以及如何预防。使用 Prepared Statements而不是纯串联。

关于php - MySQL、PHP : Select * from table where id is not in array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37212247/

相关文章:

php - 在另一个文件中使用定义常量

php - 如何启用 BCMath CentOS 6

java - 在静态 UI 中显示的动态数据

javascript - 在数组javascript中找到最小的数字

java - 访问堆栈顶部元素以递归比较两个堆栈元素是否相同的方法

arrays - 如何在 Swift 中从数组创建给定大小的唯一数组?

php - 查询数据库时使用 PHP 函数

php - Laravel 多对多关系插入

javascript - 使用mysql和nodejs更新登录日期和注销日期

mysql - 如何从此查询中删除结果?