将变量的数据库值设置为NULL而不是空字符串 [英] Setting variable's database value to NULL instead of empty string

查看:93
本文介绍了将变量的数据库值设置为NULL而不是空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的SQL数据库有很多字段像这样:
字段类型:文本Null:是默认:NULL

In my SQL database there're many fields like this: Field Type:Text Null:Yes Default:NULL

我的INSERT看起来像这样:

My INSERT looks like this:

INSERT INTO tbl (col,col,col,...) VALUES ('val','val','val',...)



现在,我的INSERT语句的值中的引号是插入字符串)到数据库当我真正想要的是什么(NULL)。

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).

所以我尝试了

if (isset($_POST['title'])) {$newTitle = mysql_real_escape_string(trim($_POST['title']));} else {$newTitle = NULL;}

,并且只插入NULL - 包含单词NULL的字符串。

and that just inserts 'NULL' - the string containing the word NULL.

我可以做些什么来确保我的NULL值正确插入?

What can I do to be certain my NULL values are inserted properly?

推荐答案

很好,但是你需要将它与一个准备的语句结合...

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(); 

如果x或newTitle为NULL,则它们将在DB中为NULL

If x or newTitle are NULL, they will be NULL in the DB

这篇关于将变量的数据库值设置为NULL而不是空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆