简体   繁体   English

MySQL更新列为空或其值

[英]mysql update column to null or its value

I am trying to update the column (LastName) to NULL, if the column has empty value, else update its value using the below mysql query. 我试图将列(LastName)更新为NULL,如果该列具有空值,则使用以下mysql查询更新其值。

$updateUserInfo = "UPDATE `UsersNew` SET MobileNo = '".$dataArray['MobileNo']."',FirstName = '".$dataArray['FirstName']."', LastName = IF(LastName = '' OR LastName IS NULL, 'NULL', LastName), EmailId = '".$dataArray['EmailId']."' where Uid = '".$uid."';";

But the LastName value is not getting updated 但是LastName值没有更新

I want if LastName is null i want the column to get updated as NULL else '".$dataArray['LastName ']."' 我想如果LastName为null,我希望该列被更新为NULL否则为'".$dataArray['LastName ']."'

Basically you need to change the section which updates LastName to this: 基本上,您需要更改将LastName更新为以下内容的部分:

LastName = " . (empty($dataArray['LastName']) ? 'NULL' : "'{$dataArray['LastName']}'") . "

Note that NULL should not be enclosed in quotes. 注意, NULL不应用引号引起来。 So your whole query becomes: 因此,您的整个查询变为:

$updateUserInfo = "UPDATE `UsersNew`
                   SET MobileNo = '".$dataArray['MobileNo']."',
                   FirstName = '".$dataArray['FirstName']."', 
                   LastName = ".(empty($dataArray['LastName']) ? 'NULL' : "'{$dataArray['LastName']}'") . ",
                   EmailId = '".$dataArray['EmailId']."'
                   WHERE Uid = '".$uid."';";

Ternary operators are nice for this: 三元运算符对此非常有用:

$updateUserInfo = "UPDATE `UsersNew` 
                   SET MobileNo = '".$dataArray['MobileNo']."',
                   FirstName = '".$dataArray['FirstName']."', 
                   LastName = ".$dataArray['MobileNo']? "'".$dataArray['MobileNo']."'":"NULL, 
                   EmailId = '".$dataArray['EmailId']."' where Uid = '".$uid."';";

Beware though, you need to clean up the input using prepared statements or PDO, otherwise your code might be subject to SQL Injection. 但是请注意,您需要使用准备好的语句或PDO清理输入,否则您的代码可能会受到SQL注入的影响。

'UsersNew' 

should not have the ' ' and be UsersNew 不应使用'',并且应该是UsersNew

Example from w3Schools : 来自w3Schools的示例:

$sql = "UPDATE MyGuests SET lastname='Doe' WHERE id=2";

Another Source: Update query PHP MySQL 另一个来源: 更新查询PHP MySQL

This in itself might not fix everything, but with the other answers in combination, it might. 这本身可能无法解决所有问题,但可以结合其他答案来解决。 Lastly, use prepared statements. 最后,使用准备好的语句。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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