How to make skip to any empty column when update data by php file to MySQL

Viewed 22

I have file PHP by this file I update the data in MySQL table. I send data to this PHP file from flutter app but there are one problem I have 3 field in this file so user can update data in those 3 Column in MySQL table to here every thing is ok but my problem if user send just one Column data from flutter app to PHP file the data will update in this Column but the others Column will will become null.

So how I can make this file make skip to any empty column the user not send data to it?

I need the old data not be changed in the database if the file does not get new data for that column.

Thank you.

PHP file:

<?php
 require_once 'con.php';

  $id = $_POST['id '];

                      $IDbook= $_POST['IDbook'];
                   $IDbookset= $_POST['IDbookset'];
            
         
$sql="UPDATE topics SET IDbook= ? ,IDbookset=? WHERE id=?";

$stmt = $con->prepare($sql); 

$stmt->bind_param("sss",$IDbook,$IDbookset,$id);

$stmt->execute();

$result = $stmt->get_result();


   $exeQuery = mysqli_query($con, $sql) ;


     if($exeQuery){
     echo (json_encode(array('code' =>1, 'message' => 'Modifier avec succee')));
}else {echo(json_encode(array('code' =>2, 'message' => 'Modification Non Terminer')));
 }


 ?>

1 Answers

One way to do it is to

  • Fetch the data for the current $id say into $OldIdbook and $OldIdbookset
  • get updated values like this $IDbook= $_POST['IDbook'] ?? $oldIDbook; This uses the old value if the $_POST is null.
  • then execute the query to update.

The second way is to construct the query by adding only the field=value pairs that have changed to the query. Its a little bit more work to handle the comma.

Related