php函数更新

php函数更新,php,function,sql-update,Php,Function,Sql Update,我已经用php创建了一个配置文件页面。该页面包括地址和电话字段,并提示用户插入其数据。然后数据保存在名为profile的表中。一切正常,但问题是表每次都会更新所有字段。我使用的功能如下: 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(my

我已经用php创建了一个配置文件页面。该页面包括地址和电话字段,并提示用户插入其数据。然后数据保存在名为profile的表中。一切正常,但问题是表每次都会更新所有字段。我使用的功能如下:

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 ){
    $update[]='`' . $field . '` = \'' . $data . '\'';   
      }

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

}
}

我的问题是,如何修改此函数的第一部分,以便如果用户仅为某个字段插入数据,则此字段仅会更新,而不是所有表。例如,假设用户插入他的电话和地址。下一次,如果用户再次使用该表单更新其个人资料,如果他更改了电话,则只有要更改的电话字段在表中显示,另一个字段包含要保留的地址。
有什么想法吗?thnx

您需要测试
$data
变量是否为空:

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());
}

和往常一样,您应该远离mysql_*函数,使用or或

您需要测试
$data
变量是否为空:

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());
}
和往常一样,您应该远离mysql_*函数,使用或