简体   繁体   English

MySQL将NULL值插入INT列

[英]MySQL Inserting NULL Value into INT Column

I know that this question has been asked before. 我知道这个问题曾经被问过。 I found the post, however, it did not solve my problem as my column does allow null. 我找到了该帖子,但是,由于我的列允许使用null,因此它无法解决我的问题。

I want to insert a NULL value into my integer column. 我想在我的整数列中插入一个NULL值。

if ($startYear == "") {
    $startYear = NULL;
}

mysqli_query($con, "INSERT INTO Application (startYear) VALUES ('".$startYear."')");

Before you ask, I have checked if $startYear is ever empty, and it is, so this should work. 在您询问之前,我已经检查$startYear是否为空,并且确实如此,因此这应该可以工作。

When I run this query it inputs a 0 into the database row. 当我运行此查询时,它将在数据库行中输入0 It does not insert NULL like I want. 它不会像我想要的那样插入NULL

Here is my column's structure: 这是我的专栏结构:

http://i.imgur.com/XuWq9Km.png http://i.imgur.com/XuWq9Km.png

One important thing is that, I can not modify the column's structure. 重要的一点是, 我无法修改列的结构。 It is off limits. 这是超限的。

Thanks in advance. 提前致谢。

The issue is you're not actually inserting into the query the string 'NULL', but a php null , which makes your query insert empty string, this gets coverted to 0 in the DB. 问题是您实际上没有在查询中插入字符串'NULL',而是php null ,这使您的查询插入了空字符串,这在数据库中被掩盖为0。

You'd need to do this: 您需要这样做:

  mysqli_query($con, "INSERT INTO Application (startYear) VALUES (NULL)");

you're inserting a PHP null value, which when used in a string context becomes an empty string - which is what was originally. 您要插入一个PHP空值,该值在字符串上下文中使用时将成为一个空字符串-原来是这样。 You have to insert a literal string with the letters n , u, l , l` for this to work: 您必须插入带有字母nu, l , l`的文字字符串,这样才能起作用:

if ($startYear == '') {
   $startYear = 'NULL'; // string null
}
$sql = "INSERT ..... VALUES ($startYear)";

which would produce 会产生

INSERT ... VALUES (NULL)

To expand: 扩张:

   $foo = null; // actual PHP null value
   $bar = "$foo"; // insert this php null into a string
   echo strlen($bar); // returns 0

   $foo = 'null' // string with 4 letters: n,u,l,l
   $bar = "$foo";
   echo strlen($bar); // returns 4

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

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