I have large tables in my database and instead of specifying each column name I am trying to build the query dynamically.
I am trying to do an update in the 'motherboard' table based on the POST data received. The $data object i receive has more fields than the table has. (I added some fields for some flags.)
Hence, I am retrieving the record I'm about to update and by comparing each of it's columns with my $data object fields I am constructing the UPDATE query.
I'm new to php, therefore I don't know the syntax well.
This is the code:
<?php
$data = json_decode($_POST["data"], true);
$id = $data["ID"];
include_once 'dbconnect.php';
$query = sprintf("SELECT * FROM `motherboard` WHERE ID = " . $id . ";");
$result = mysqli_query($con, $query);
$existingData = mysqli_fetch_assoc($result);
include_once 'dbclose.php';
$statement = "";
$statement = "UPDATE motherboard SET ";
$flag = false;
foreach ($existingData as $key => $value) {
    if ($existingData->$key != $data->$key) {
        $statement .= $key . " = " . $data->$key . " , ";
        $flag = true;
    }
}
if ($flag)
    $statement = substr($statement, 0, strrchr($statement, ',') - 1);
$statement .= " WHERE ID = " . $id . ";";
echo $statement;
?>
My main problem is in the foreach loop. I don't know how can I compare and then use for building the query the $existingData and $data variables. 
How can I achieve this?
 
     
     
    