隔离已更新的字段

I'm trying to check whether an existing field have been changed and identify it so i can later add it into a changes table. Any idea on how to do so?

 if (isset($_POST['submit'])) 
    {
        $sql = "SHOW COLUMNS FROM Employees";
        $result = mysqli_query($con,$sql);
         while($row = mysqli_fetch_array($result)){
                    $tempname = $row['Field'];
                    $sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";
                    $result2 = mysqli_query($con,$sql2);
                    if ($con->query($sql2) === TRUE) {
                    } else {
                        echo "Error: " . $sql2 . "<br>" . $con->error;
                        echo '<script>swal("Error", "Something went wrong '.$con->error.'", "error");</script>';
                    }

First of all I think you have missed a ".$var." in this line:

$sql2 = "UPDATE Employees SET ".$row['Field']."= '$_POST[$tempname]' WHERE AFNumber='".$_GET["af"]."'";

it should be like this:

$sql2 = "UPDATE Employees SET ".$row['Field']."= '".$_POST[$tempname]."' WHERE AFNumber='".$_GET["af"]."'";

you could do a select query first to diff against the data you want to update

// get the rows that will be changed
$sqlOldData = "SELECT * FROM Employees WHERE AFNumber='".$_GET["af"]."' AND (".$row['Field']." NOT LIKE '".$_POST[$tempname]."')";

and then update the table.


Q: But one question, as for integrating it in the code, any help please, i'm just starting in this area:

$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '$login_session', '', '$_POST[$tempname]')";

NOTE: First of all you missed again some string breakouts:

  • '$login_session' --> '".$login_session."'
  • '$_POST[$tempname]' --> '".$_POST[$tempname]."'

so you get:

$sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '', '".$_POST[$tempname]."')";

A: adoption $resultOldData is the result of $sqlOldData

this should work:

while($rowOldData = mysqli_fetch_array($result))
{
    $sql3 = "INSERT INTO Changes (Table, AFNumber, Attribute,DateChanged,HRUser,OldValue,NewValue) VALUES ('Employees', '".$_GET["af"]."', '".$row["Field"]."', '".date('dd/m/Y HH:mm:ss')."', '".$login_session."', '".$rowOldData[$row['Field']]."', '".$_POST[$tempname]."')";
    mysqli_query($con,$sql3);
}