I am in the process of comparing two tables for differences and insert the original with what has changed into a new table. The only exception is that I don’t want to look at the last_update_date as I have found this may change without any changes to the record/row itself.
My issue is that this script is working across a variety of tables and as I loop through the results I am getting the keys and values, I do know that last_update_date and id are consistent though as columns.
I have tried using array_dif, but when it did find differences it would error out some way down due to “Insert value list does not match column list.”
I have tried using code like $column !== $column and then executing the queries. The problem with this approach is that it inserts the data for the first array, and then only inserts one column for the second when I need all of them (a to compare and b sometimes, the value may be NULL so I need to see the before and after).
What I have below is one of many of today’s iterations, but simply I just want to insert rows from the first if the second has the same id but one of the other columns is not the same (but not based on the last update date). Thanks in advance:
//Set the arrays up
$prep = array();
$prep2 = array();
//We have run the sql
foreach ($database1_sql_row as $result) {
foreach ($result as $column => $column_value) {
/*
*
*
* append the column and column value to the array
*
*
*/
$prep[':'.$column] = $column_value;
/*
* Run the SQL to get the results from the second table where id = id of the first
*
*/
$database2_sql_row=$database2_sql->fetchAll(PDO::FETCH_ASSOC);
/*
*
*
*
* Setup the second array for inserting the values that don't match
*
*
*/
foreach ($database2_sql_row as $result2) {
foreach ($result2 as $column2 => $column_value2) {
$prep2[':'.$column2] = $column_value2;
if($column2 !== "last_update_date"){
//do something here so that if this is the only change we don't insert both result 1 and 2
}
}
}
}
$aDifferenceArray = array_diff($result, $result2);
if(!empty($aDifferenceArray)){
$sth = $DB_con3->prepare("INSERT INTO $insert_table ( " . implode(', ',array_keys($result)) . ") VALUES (" . implode(', ',array_keys($prep)) . ")");
$res = $sth->execute($prep);
$sth2 = $DB_con3->prepare("INSERT INTO $insert_table ( " . implode(', ',array_keys($result2)) . ") VALUES (" . implode(', ',array_keys($prep2)) . ")");
$res2 = $sth2->execute($prep2);
}
}