简体   繁体   中英

MySQL update column only if value not empty where

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

Only if the data is POST from front end form. If data not POST don't 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...

Try it with 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."' ";

or :

  $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."' ";

Not sure to understand: you have data and want to update, but only if some fied in the DB are empty? In the case perfom only a where:

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

for example

$query = 'UPDATE user SET

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

  WHERE `id` = "'.$id.'"';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM