0

我在 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());

}

}
4

3 回答 3

1

如果数据不为空,您只会更新该字段。

看到这一行:

if(!empty($data)){
于 2013-03-03T16:39:50.333 回答
1

因为您明确地忽略了空值:

if(!empty($data))
于 2013-03-03T16:40:56.350 回答
0

由于 empty() 函数可以验证缺失和错误的元素,因此您不能简单地将其传递给 SQL 查询。因此,如果您想实际为这些项目生成查询,则需要通过执行以下操作显式设置值:

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

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

$update[] = (empty($data)) ? "`{$field}` = ''" : "`{$field}` = '{$data}'";
于 2013-03-03T17:05:13.637 回答