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,
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.