MySQL update column only if the value is not empty, where

I have an UPDATE query and using Ajax, I wanted to know if any value is empty, I can only update the values ​​that are not empty in the database. I don't know if it is possible to have an if statement or something to check, to skip empty values. I know that I can just add another form element, but I just wanted to find out if there is another solution.

Only if the data is POST from the front end form. If the non-POST data does not update this Title= '. $ Title. ',

$id = $_POST['id'];
$title = "";
$description = $_POST['Description'];
$date = $_POST['Date'];

 $query = 'UPDATE user SET

  `id` = '.$id.', 
  `Title` = '.$title .', 
  `Description` = '.$description.', 
  `Date` = '.$date =.' 
  WHERE `id` = '.$id;

 $result = mysql_query($query) or die("<b>A fatal MySQL error occured</b>.<br />Query:  ".$query."<br />Error: (".mysql_errno().") ".mysql_error());

Update: This is what worked for me. Thanks Karim Daraf

$ query = "UPDATE user SET       Title= Coalesce ($ title, Title) etc.

+4
3

Coalesce.

   $query = " UPDATE user 
   SET 
 `Title`       = CASE WHEN `Title`='' or `Title` IS NULL THEN '$title' END, 
 `Description` = CASE WHEN `Description`='' Or `Description` IS NULL THEN '$description' END, 
  `Date`       = CASE WHEN `Date`='' Or Date` IS NULL THEN '$date' END
    WHERE `id` = '".$id."' ";

:

  $query = " UPDATE user 
  SET 
 `id`         = Coalesce('$id''".$id."' , NULLIF(`id`,'')), 
`Title`       = Coalesce('$title''".$title."',NULLIF(`Title`,'') ) , 
`Description` = Coalesce('$description''".$description."' , NULLIF(`Description`,'') ) , 
 `Date`       = Coalesce('$date''".$date."',NULLIF(`Date`,'')) 
 WHERE `id` = '$id''".$id."' ";
+5

, : , ? perfom a :

 $query = 'UPDATE user SET
  `id` = '.$id.', 
  `Title` = '.$title .', 
  `Description` = '.$description.', 
 `Date` = '.$date =.' 
  WHERE `id` = '.$id.' AND Title = '';

+1
$query = 'UPDATE user SET

  'id' = '.$id.', 
  'Title' = COALESCE(NULLIF("'.$title.'", ""),'Title'), 
  'Description' = "'.$description.'", 
  'Date' = "'.$date.'" 

  WHERE 'id' = "'.$id.'"';
+1
source

Source: https://habr.com/ru/post/1617507/


All Articles