将JSON与MySQL数据库进行比较以获取删除的记录

时间:2019-07-01 06:45:15

标签: php mysql json

我已经设置了一个JSON解析器,该解析器使用PHP将事件添加到MySQL数据库。我检查JSON文件中的所有事件的ID,以查看它是否已存在于数据库中,如果存在,则仅更新某些数据。如果事件不存在,则会将其添加到数据库中。

所有方法都运行良好,但是一个问题是我不知道是否有事件已从JSON文件中删除,但之前已导入到数据库中。导入每周运行一次,因此上周可能添加了一个事件,现在该事件已被取消,因此我想停用这些事件(数据库中有一个Status标志)。

我尝试为此设置一个单独的查询($ check_removed),但无法正常工作,它似乎无能为力。在查询中,我还添加了一项检查,仅查找即将发生的事件,因为比今天更早的事件不相关。

这是我的代码,经过简化:

$filename = "events.json";
$data = file_get_contents($filename);
$array = json_decode($data, true);

foreach ($array as $row) {
 $id = $row["id"];
 $title = $row["title"];
 $date = $row["date"];

 // Get current date for comparison of removed records
 $today = date("Y-m-d");

 $check = mysqli_query($connect,"SELECT * FROM `events` WHERE `ID` = '".$id."'"); 
 $check_removed = mysqli_query($connect,"SELECT * FROM `events` WHERE `date` >= '".$today."' AND `ID` != '".$id."'");  

 if(mysqli_num_rows($check_removed)==1) {
  // Upcoming event found in database but not in JSON (doesn't work)
 } elseif(mysqli_num_rows($check)==1) {
  // Existing ID matches, only update event (this works)
 } else {
  // No existing ID matches, add new event (this works)
 }
}

有什么想法我在做什么错吗?

1 个答案:

答案 0 :(得分:1)

感谢您将我推向正确的方向!它帮助我找到了another post,可以对其进行修改以使其起作用。

$FutureRecords = mysqli_query($connect,"SELECT `ID` FROM `events` WHERE `date` >= '".$today."'");

$FutureRecords_TempArray1 = array();
$FutureRecords_TempArray2 = array();

foreach ($FutureRecords as $row) { // Push local table id's in empty array
    array_push($FutureRecords_TempArray1, $row["ID"]);
}
foreach ($array as $row) { // Push JSON data id's in empty array
    array_push($FutureRecords_TempArray2, $row["ID"]);
}
// Add a joint array excluding excess records.
$FutureRecords_Query = array_intersect($FutureRecords_TempArray2,$FutureRecords_TempArray1);

// Update data in live table where ids are not present in new joint array
$DeactivateRemovedRecords = mysqli_query($connect,"UPDATE `events` SET `Active` = 0 WHERE `Start` >= '".$today."' AND `ID ` NOT IN ('" . implode( "', '" , $FutureRecords_Query ) . "' )");