仅在有新值时更新条目

时间:2014-03-09 14:38:34

标签: php mysql

我有一个表单,它将更新mysql表中的指定条目。只有填写了所有字段,表单才会提交。

有没有办法让表单只更新具有新值的字段并保留空白的字段?

表格代码:

    <?php
error_reporting(E_ALL ^ E_DEPRECATED);
if(isset($_POST['update']))
{
$con = mysql_connect($server, $db_user, $db_pass);
if(! $con )
{
 die('Could not connect: ' . mysql_error());
}

$id = $_POST['id'];
$english = $_POST['english'];
$math = $_POST['math'];
$science = $_POST['science'];

$table = $_POST['year'];


$sql = "UPDATE $table ".
       "SET english = $english ,math = $math ,science = $science ".
        "WHERE id = $id" ;
mysql_select_db('education');
$retval = mysql_query( $sql, $con );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
//header("Location: " . $_SERVER['PHP_SELF']);
//echo "Entered data successfully\n";
mysql_close($con);
}
else
{
?>
<?php } ?>
    <h4 align="center">Update student details</h4>
    <form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
      Student ID:
      <input name="id" type="text" id="id">
      <br>
      English mark:
      <input name="english" type="number" id="english">
      <br>
      Math's mark:
      <input name="math" type="number" id="math">
      <br>
      Science mark:
      <input name="science" type="number" id="science">
      <br>
      Year: <br>
      <select name="year" id="year">
        <option value="">Select...</option>
        <option value="year1">Year 1</option>
        <option value="year2">Year 2</option>
        <option value="year3">Year 3</option>
        <option value="year4">Year 4</option>
      </select>
      <br>
      <br>
      <input name="update" type="submit" id="update" value="Submit">
    </form>

2 个答案:

答案 0 :(得分:0)

在使用查询中的变量之前使用isset()

答案 1 :(得分:0)

试试这个:

$sql = "UPDATE $table ".
   "SET english = $english ,math = $math ,science = $science ".
    "WHERE id = $id AND (english != $english OR math != $math OR science != $science)";