简体   繁体   English

PHP PDO-在mysql中更新仅发布值(html格式)

[英]PHP PDO - Update in mysql only posted value (html form)

I have an html form that has some disabled field depending of what kind of authorization the user have. 我有一个html表单,其中有一些禁用字段,具体取决于用户具有哪种授权。 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. 当我按Submit时,脚本应该了解发布的是哪个表单字段,哪些不是,然后仅更新数据库中的相关字段。

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. 我可以修改BirthdayBirth placesex ,但是NameSurname被禁用,因此不会通过html表单发布。 Therefore have to be updated only Birthday , BirthPlace , Sex where id = $idperson . 因此, BirthPlace更新BirthdayBirthPlaceSex ,其中id = $idperson But if I have permission, I post Name and Surname too. 但是,如果获得许可,我也会发布NameSurname And therefore I should update also these value. 因此,我也应该更新这些值。

Is there a fast way to do it with PDO? 有使用PDO的快速方法吗? Or I have to create a long sequence of if/else? 还是我必须创建较长的if / else序列?

Sorry for my bad english 对不起,我的英语不好

The Best and easy way to do this, 最好,最简单的方法

  • First collect post data and check id is set 首先收集帖子数据并设置检查ID
  • fetch all data from your table using id 使用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. 希望这段代码对您有所帮助,祝您编程愉快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM