Setting variable's database value to NULL instead of empty string

寵の児 提交于 2019-12-11 05:30:37

问题


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

My INSERT looks like this:

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

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.

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


回答1:


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




回答2:


You can try by adding a NULL without the quotes example below:

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.




回答3:


Don't specify the field in INSERT INTO or provide a value. If you have 3 fields, f1 f2 f3 And you

INSERT INTO tbl (f1, f3) VALUES ('something', 'something')

Then f2 will not be inserted and default to null.




回答4:


I use '0' instead of null. When you use if statements you can run queries like

if($row['f2'] == 0){...

Rather than null :)



来源:https://stackoverflow.com/questions/8096648/setting-variables-database-value-to-null-instead-of-empty-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!