简体   繁体   中英

update data in php if the input is filled

I want to create a form for editing the user's data and send the data that user wants to change to DB via UPDATE query, and just those data must be sent that the user has filled them, for example, if the user doesn't want to edit the address so it must not be sent to MySQL.

How can I write a code for these? Could anyone explain the algorithm for me :)

Sincerely

Note: Here is the form that user will use to update the info

<form method="post" class="form-group" action="edit-users.php">
    <label for="name">Name</label>
    <input type="text" class="form-control" name="name">
    <label for="email">E-mail Address</label>
    <input type="email" class="form-control" name="email">
    <label for="telnr">Telephone Number</label>
    <input type="tel" name="telnr" class="form-control">
    <label for="address">Address</label>
    <input type="text" class="form-control" name="address">
    <br>
    <input type="submit" class="btn btn-primary" name="submit" value="Save Changes">
</form>
<?php
if(isset($_POST['name']) AND !empty($_POST['name'])) {
      $name = $_POST['name'];
      $insertbd = $bdd->prepare("UPDATE membres SET name = ? WHERE id = ?");
      $insertbd->execute(array($name, $_SESSION['id']));      
}
?>

for example with the name input you can do like that, the "!empty" or isset if an area rest blank nothing will change in your DB instead when a user changes something and fill the form

cheers

build your query according to the data you have. data you don't have is empty, so it will be like:

<?
$q="UPDATE $table_name SET "
$vals=array();
if(isset($_POST['address']) && !empty($_POST['address'])) {
    $vals[]='address= $_POST['address']';
}

... same for all the other fields ...

$q .= implode(',',$vals);
$q .= "WHERE $condition";

and then just run the sql command

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.

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