Reputation: 91
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']
Upvotes: 0
Views: 158
Reputation: 2711
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);
Upvotes: 1
Reputation: 158
if($dataArray['password'])
{
$condition=" , `password` = '".$dataArray['password']."'"; } else
{
$condition="";
}
$sql= "UPDATE `my_tbl` SET `username`= '".$dataArray['username'] ."' ".$condition." WHERE `id` = ".$dataArray['id'];
Upvotes: 1
Reputation: 1327
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;
Upvotes: 1