1

这里有张桌子:

|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
}
?>
   } 

在这种形式中,我需要更新所有字段,否则,更新的表可以有空值。例如,我想要更新姓名字段,但保留姓氏,通过电子邮件发送现有值。想法?

4

2 回答 2

0

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.

于 2013-02-27T13:09:17.643 回答
0

可以尝试这样的事情:

$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'";

虽然这是未经测试的。

于 2013-02-27T12:49:47.903 回答