1

I have create a profile page in php. The page includes the address and telephone fields and prompts the users to insert their data. Data are then saved in my table named profile. Everything works fine, but the problem is that the table updates all fields each time. The function that I use is the following:

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

}

}

My question is, how can I modify the first part of this function, so that if the user inserts data only for a certain field, this field only to be updated and not all the table. For example lets say that the user inserts his telephone and address. The next time if the user uses again the form to update his profile, if he change his telephone, only the telephone field to change in table and the other that includes his address to remain at it was. Any ideas? thnx

1 Answer 1

1

You need to test if the $data variable is empty:

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

And as always you should move away from mysql_* functions, and use either MySQLi or PDO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.