0

I want to update my password field only if there's a password (not NULL) in input but at the same time, 'username' can update in the table.

This is my current PHP code:

UPDATE `my_tbl` 
SET `username`= '".$dataArray['username']."', `password` = IF( IS NULL('".$dataArray['password']."'),  
   `password`, '".$dataArray['password']."') 
WHERE `id` = ".$dataArray['id']
3
  • password = coalesce(passwordparam, password) Commented Nov 25, 2016 at 8:19
  • IF should be IIF? Commented Nov 25, 2016 at 8:23
  • @RST Please don't assume Commented Nov 25, 2016 at 9:50

3 Answers 3

1

Use concatenation to solve this

$sql= UPDATE `my_tbl` SET `username`= '".$dataArray['username']."', 
                    `password` = IF( IS NULL('".$dataArray['password']."'),  `password`, '".$dataArray['password']."')
                    WHERE `id` = ".$dataArray['id'];

Change this query into

 $condition="";
    if($dataArray['password'] != ""){
       $condition=" , `password` = '".$dataArray['password']."'";
    }

     $sql= "UPDATE `my_tbl` SET `username`= '".$dataArray['username'] ."' ".$condition."
                        WHERE `id` = ".$dataArray['id'];
                        echo $sql;
Sign up to request clarification or add additional context in comments.

Comments

1
if($dataArray['password'])       
{
$condition=" , `password` = '".$dataArray['password']."'";   }  else 
{    
$condition="";    
}    
$sql= "UPDATE `my_tbl` SET `username`= '".$dataArray['username'] ."' ".$condition."  WHERE `id` = ".$dataArray['id'];

2 Comments

why you repeated the answer?
sorry, same code but modified some times without comma might gives error before concatenate..
1

With codeigniter active records :

$data['username'] = $dataArray['username'];

if(!empty($dataArray['password'])) {
    $data['password'] = $dataArray['password'];
}

$this->db->where('id', $dataArray['id']);
$this->db->update('my_tbl',$data); 

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.