简体   繁体   中英

MySQL update fields only if they are empty or NULL

I have a really lengthy UPDATE query

$sql = "UPDATE table SET
field_1 = '$field_1',
field_2 = '$field_2',
field_3 = '$field_3'

...

WHERE id = '$id'
";

I want the update to happen only if the target field is empty or NULL. I think I could use something like this:

UPDATE table SET field_1 = '$field_1' WHERE field_1 IS NULL OR field_1 = ''

But how can I apply it to all the fields at once?

Yes, I believe this is possible. You can use the IF() function to achieve this.

UPDATE `table` SET field_1 = IF(field_1 IS NULL or field_1 = "", ?, field_1), field_2 = IF(field_2 IS NULL or field_2 = "", ?, field_2)

Please note the? in the query as these are placeholders for prepared statements

Which you should seriously consider particularly when using user input. an example may look like

$conn = new PDO; // configure this class accordingly.

$query = $conn->prepare("select * from table where field = ? and field_2 = ?");
try {
$query->execute(array($value1, $value2));
} catch (PDOException $e) {
   $e->getErrors(); // Do what you want to do with this log, print etc.
}

$results = $query->fetchAll(PDO::FETCH_ASSOC); // This will return an array of results.
$result = $query->fetch(PDO::FETCH_ASSOC); // This will return the first result.

The above is merely an example of how you could achieve a query which prevents sql injection, please read about it here for more information, and consider adopting it

https://www.php.net/manual/en/pdo.prepare.php

https://www.php.net/manual/en/mysqli.prepare

I would just split the update into three separate queries.

UPDATE table SET field_1 = '$field_1' WHERE field_1 IS NULL OR field_1 = '';

UPDATE table SET field_2 = '$field_2' WHERE field_2 IS NULL OR field_2 = '';

UPDATE table SET field_3 = '$field_3' WHERE field_3 IS NULL OR field_3 = '';

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