[英]Setting variable's database value to NULL instead of empty string
In my SQL database there're many fields like this: Field Type:Text Null:Yes Default:NULL 在我的SQL数据库中,有许多类似这样的字段:字段类型:文本Null:是默认值:NULL
My INSERT looks like this: 我的INSERT看起来像这样:
INSERT INTO tbl (col,col,col,...) VALUES ('val','val','val',...)
Now, those quotes in my INSERT statement's values are inserting '' (empty string) in to the database when what I really want is nothing (NULL). 现在,我的INSERT语句的值中的引号是在我真正想要的东西(NULL)时将''(空字符串)插入到数据库中。
So I tried 所以我试过了
if (isset($_POST['title'])) {$newTitle = mysql_real_escape_string(trim($_POST['title']));} else {$newTitle = NULL;}
and that just inserts 'NULL' - the string containing the word NULL. 并且只插入'NULL' - 包含单词NULL的字符串。
What can I do to be certain my NULL values are inserted properly? 如何确定我的NULL值正确插入?
You can try by adding a NULL without the quotes example below: 您可以尝试添加不含以下引号示例的NULL:
INSERT INTO tbl (col,col,col,...) VALUES (NULL,'val','val',...)
Also make sure the column that you want to have a pure null must have the allowed NULL ticked. 还要确保要具有纯null的列必须勾选允许的NULL 。
What you have is fine, but you need to combine it with a prepared statement... 你有什么是好的,但你需要将它与准备好的声明结合起来......
// prepare the statement
$stmt = $mysqli->prepare("INSERT INTO tbl (title, x,y,z) values (?,?,?,?)");
$stmt->bind_param($newTitle, $x,$y,$z);
$x = 'hello, world';
// execute prepared statement
$stmt->execute();
If x or newTitle are NULL, they will be NULL in the DB 如果x或newTitle为NULL,则它们在DB中将为NULL
Don't specify the field in INSERT INTO or provide a value. 不要在INSERT INTO中指定字段或提供值。 If you have 3 fields, f1 f2 f3 And you 如果您有3个字段,则f1 f2 f3
INSERT INTO tbl (f1, f3) VALUES ('something', 'something')
Then f2 will not be inserted and default to null. 然后不会插入f2并默认为null。
I use '0' instead of null. 我使用“ 0”而不是null。 When you use if statements you can run queries like 当您使用if语句时,您可以运行类似的查询
if($row['f2'] == 0){...
Rather than null :) 而不是null :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.