PHP PDO - 在mysql中更新仅发布值(html表单)

I have an html form that has some disabled field depending of what kind of authorization the user have. When I press submit, the script should understand which form field are posted and which not, and then update only the related field in the database.

For example:

I can modify Birthday, Birth place and sex, but Name and Surname are disabled and so are not posted by the html form. Therefore have to be updated only Birthday, BirthPlace, Sex where id = $idperson. But if I have permission, I post Name and Surname too. And therefore I should update also these value.

Is there a fast way to do it with PDO? Or I have to create a long sequence of if/else?

Sorry for my bad english

The Best and easy way to do this,

  • First collect post data and check id is set
  • fetch all data from your table using id
  • loop your post data and check with collected details
  • if collected details value and post value changed update in collected details variable
  • update all your fields with new collected array

Check the below code for more understanding

function collect() {
   if(isset($_POST['id'])) {
      // validate id and get all details from table
      $details = getDetails($_POST['id']);
      foreach($_POST as $key=>$value) {
        // loop your post data and check with collected details if value changed update in collected details 
         if(array_key_exists($key, $details)) {
            $details[$key] = ($details[$key] != $_POST[$key]) ? $_POST[$Key] : $details[$key];
         }
      }
   } else {
      echo "id not found to update";
   }
}

function getDetails($id) {
   $query = "SELECT * FROM table_name WHERE id=:id";
   $stmt = $conn->prepare($query);
   $stmt->bindParam(':id', $id);
   $stmt->execute();
   return $stmt->fetch(PDO::FETCH_ASSOC);
}


function update($details) {
   $query = "UPDATE table_name SET field_1=:field_1, field_2=:field_2, all_field=:all_field WHERE id=:id";
   $stmt = $conn->prepare();
   $stmt->bindParam(':field_1', $details['field_1']);
   ...
   $stmt->bindParam(':id', $details[$id]);
   return $stmt->execute();
}

Hope this code helps you, Happy coding.