表单保存空值php


form save empty value php

我在php中创建了一个配置文件页面,其中用户使用表单可以将他的电话号码保存在数据库中名为profile的表中。如果用户决定更改他的电话号码可以很容易地去表单更改它并再次保存它。我唯一的问题如下。假设用户想要删除他的电话号码。如果他转到表单删除他的号码(使该字段为空)并按保存,则电话号码不会更改为空值,而是继续保持以前的号码。任何想法如何改变这一点,以保持一个空值?

这是我的代码的形式:
<form   action=""   method="POST"  >    
<?php
if ( isset($_GET['success']) === true && empty($_GET['success'])===true ){
   echo'Profile Updated Sucessfuly';
    }else{
   if( empty($_POST) === false  &&  empty($errors) === true ){
     $update_data_profile = array('telephone' => $_POST['telephone']);
          update_user_profile($session_user_id, $update_data_profile);
      header('Location: profile_update.php?success');                               
      exit();
   }else if ( empty($errors) === false ){
      echo output_errors($errors);
       }
     ?>
 Telephone<input name="telephone" type="text" size="25"  value="<?php echo $user_data_profile['telephone']; ?>"/>
<input type="submit" value="" name="submit"/>
</form> 

这是我的函数调度数据到配置表:

function update_user_profile($user_id, $update_data_profile){
  $result = mysql_query("select user_id from profile where user_id = $user_id limit 1");
  if(mysql_num_rows($result) === 1){
  $update = array();
      array_walk($update_data_profile, 'array_sanitize');
  foreach($update_data_profile as $field => $data ){
    if(!empty($data)){
      $update[]='`' . $field . '` = ''' . $data . '''';
    }
  }
  if(isset($update) && !empty($update)){
  mysql_query(" UPDATE `profile` SET " . implode(',  ', $update) . " WHERE `user_id` = $user_id ") or die(mysql_error());
}
   }
  else{
$user_id = $update_data_profile['user_id'] ;
if(count($update_data_profile)){
$columns = array();
$values = array();
    foreach($update_data_profile as $field => $data){
    $columns[] = $field;
    $values[] = $data;
    } 
}
mysql_query(" INSERT INTO `profile` (" . implode(",", $columns) .") values ('" . implode("','", $values) . "')" ) or die (mysql_error());
}
}

只有当数据不为空时才更新字段。

见这一行:

if(!empty($data)){

因为你显式地忽略了空值:

if(!empty($data))

由于empty()函数可以验证缺失和false元素,因此不能简单地将其传递给SQL查询。因此,如果您想为这些项生成查询,则需要显式地设置值,方法如下:

if (empty($data)) {
    $update[] = "`{$field}` = ''" ;
} else {
    $update[] = "`{$field}` = '{$data}'" ;
}

如果你正在为PHP 5.3或更高版本编写,你也可以替换If ..else语句,并通过使用三元操作符(条件赋值)来缩短代码,如下所示:

$update[] = (empty($data)) ? "`{$field}` = ''" : "`{$field}` = '{$data}'";