[英]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. 我可以修改Birthday
, Birth place
和sex
,但是Name
和Surname
被禁用,因此不会通过html表单发布。 Therefore have to be updated only Birthday
, BirthPlace
, Sex
where id = $idperson
. 因此, BirthPlace
更新Birthday
, BirthPlace
, Sex
,其中id = $idperson
。 But if I have permission, I post Name
and Surname
too. 但是,如果获得许可,我也会发布Name
和Surname
。 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, 最好,最简单的方法
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.