简体   繁体   English

如何防止MySQL使用空字符串更新列?

[英]How do I prevent MySQL from updating column with empty string?

I have a form to update details of a user and they do not have to fill in every field. 我有一个表单来更新用户的详细信息,他们不必填写每个字段。 Because of that, it will be passing an empty string to the database via POST. 因此,它将通过POST将空字符串传递给数据库。 This is my query: 这是我的查询:

$q = "UPDATE mdl_user SET firstname='$fname', lastname='$lname', email='$email',
      address='$address', city='$city', school='$school', phone1='$phone'
      WHERE id='$uid'";

Is there a way for MySQL to check if for example $fname is an empty string and if it's empty don't update that field? 有没有办法让MySQL检查例如$fname是否为空字符串,如果它为空则不更新该字段?

If not then how should I go about doing this in PHP? 如果没有那么我应该如何在PHP中执行此操作?

You can use IF statement for each field you need to check. 您可以对需要检查的每个字段使用IF语句。 For example : 例如 :

$q = "UPDATE mdl_user SET firstname=IF(LENGTH('$fname')=0, firstname, '$fname'), lastname=IF(LENGTH('$lname')=0, lastname, '$lname'), email=IF(LENGTH('$email')=0, email, '$email'), address='$address', city='$city', school='$school', phone1='$phone' WHERE id='$uid'";

I would do this 我会这样做的

<?php
if ($fname) {
 $fname = "firstname='$fname',";
} else {
 $fname = '';
}
$q = "UPDATE mdl_user SET $fname lastname='$lname', email='$email', address='$address', city='$city', school='$school', phone1='$phone' WHERE id='$uid'";
?>

But you should really be worried about how insecure your code is. 但你真的应该担心你的代码有多不安全。

首先运行SELECT语句并执行mysql_num_row()如果返回值> 0然后退出()

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

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