简体   繁体   中英

Php MySQL update html form

There is a table:

|id name surname email    |
|1  john surjohn @mail.com|
|2  peter pet    @mail.com|                   
|.........................|

PHP:

<?php
if(isset($_POST['update']))
{
...
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());

}

$id = $_POST['id'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$mail = $_POST['mail'];

$sql = "UPDATE emps ".
       "SET name= '$name', surname'$surname', email='$mail' ".
       "WHERE Id = $id" ;
mysql_select_db('dbase');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not update data: ' . mysql_error());
}
echo "blablablabla ! \n";
mysql_close($conn);
}
else

{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
    <fieldset style="width: 350px" >
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Id </td>
<td><input name="id" type="text" id="id" value=""></td>
</tr>
<tr>
<td width="100">name</td>
<td><input type="text" maxlength="15" name="name" value="" ></td>
</tr>
<tr>
<td width="100">surname</td>
<td><input type="text" maxlength="40" name="surname" value="" ></td>
</tr>
<tr>

<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="update">
</td>
</tr>
</table>
        </fieldset>
</form>
<?php
}
?>
   } 

In this form i need update all fields otherwise, updated table can have null values. I want for example, update name field, but leave surname, email existing values. ideas?

Could try something like this:

$id = $_POST['id'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$mail = $_POST['mail'];

$sql = "UPDATE emps SET";
$moresql = '';

if(isset($name) && !empty($name)) {
    $moresql .= " name = '$name'";  
}

if(isset($surname) && !empty($surname)) {
    if ($moresql) $moresql .= ',';
    $moresql .= " surname = '$surname'";    
}

if(isset($mail) && !empty($mail)) {
    if ($moresql) $moresql .= ',';
    $moresql .= " mail = '$mail'";  
}

$sql .= $moresql;
$sql .= " WHERE Id = '$id'";

This is untested though.

Karl's idea is the way to go, but it can be refactored this way:

$id = $_POST['id'];

$sql = "UPDATE emps SET";
$fieldValuePairs = array();

foreach($_POST as $key => value)
    if($key != 'id')
       $fieldValuePairs[] = "'$key' = '$value'";

$sql .= " ". implode(',', $fieldValuePairs)." WHERE id = $id";

Note: this works only if you use input names (in the form) equal the column names (in the database).

Have a great day.

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