What I am doing in the code is basically getting all the ids currently in mysql database. Getting the ids from a JSON array. Comparing them and deleting the ids in the mysql table that are NOT in the JSON array.
<?php
Getting POST Data (Works)
$test = $_POST["data"];
$obj = json_decode($test, true);
$data = $obj["myarray"];
First sql query (Works)
$sql3 = "select id from pbs";
$current_ids= mysqli_query($connection, $sql3)
initialize arrays for IDs (Works)
$ids_array= array();
$ids_array2= array();
Get current set of ids from mysql table and putting them in ids_array (Works)
while($row = mysqli_fetch_array($current_ids)){
$ids_array[] = $row['id'];
}
Looping over each JSON array $data i.e [{$val}, {$val}, ...]
foreach($data as $val){
This is one of the things I'm unsure about. Can I push each id value into and array? i.e:
if $val = {"id": "1", ...} $ids_array2 should have the value "1". If this is correct, I should have an array of new ids that I got from the JSON array.
array_push($ids_array2, $val->id);
checks if row is in table by id. If it is, update the mysql row. If it is not, insert a new mysql row (Works)
$check = mysqli_query($connection,"SELECT * FROM `pbs` WHERE `id`='".$val["id"]."'");
if(mysqli_num_rows($check)==1){
//Update the row
}
else{
//Insert the row
}
}
For each item in $ids_array (current set of ids from mysql table). Delete it from table if it is not in $ids_array2 (newset of ids from JSON) where id = $item (Does not work)
foreach($ids_array as $item){
if(in_array($item, $ids_array2)==0){
$sql5 = "DELETE FROM pbs WHERE id='"$item"'";
$delete= mysqli_query($connection, $sql5);
}
}
mysqli_close($connection);
?>
So what I am trying to do is INSERT, UPDATE and DELETE records depending on the JSON array I get from the client. Thanks!