MySQL没有插入NULL值

时间:2013-09-18 13:32:53

标签: php mysql null

这对你来说很容易,但我是菜鸟,所以我需要帮助。

这是我的代码,无论出于何种原因,else语句都没有执行。如果我更改$ variable = NULL的NULL值,它会工作,但是在我的数据库中输入一个空字符串而不是NULL值。任何人都可以帮忙解决原因吗?

if (isset($_POST['agreeto']))
{
    $enter_feedback = "INSERT INTO feedback" . //(initial, surname, country_id, date, friend_score, return_score, service_score, comments)
        " VALUES('" . $initial. "', '" . $lastname . "', '" . $country_id . "', NOW(),  '" . $friend . "', '" . $return . "', '" . $service . "', '" . $_POST['comments'] . "')";
}else
{
    $enter_feedback = "INSERT INTO feedback" . //(initial, surname, country_id, date, friend_score, return_score, service_score, comments)
    " VALUES('" . $initial. "', '" . $lastname . "', '" . $country_id . "', NOW(),  '" . $friend . "', '" . $return . "', '" . $service . "', " . NULL . ")" or die("couldn't execute my query");
}

4 个答案:

答案 0 :(得分:3)

MySQL需要string = NULL,并且你传递的是php NULL常量的值。

if (isset($_POST['agreeto']))
                {
                    $enter_feedback = "INSERT INTO feedback" . //(initial, surname, country_id, date, friend_score, return_score, service_score, comments)
                    " VALUES('" . $initial. "', '" . $lastname . "', '" . $country_id . "', NOW(),  '" . $friend . "', '" . $return . "', '" . $service . "', '" . $_POST['comments'] . "')";
                }else
                    {
                        $enter_feedback = "INSERT INTO feedback" . //(initial, surname, country_id, date, friend_score, return_score, service_score, comments)
                        " VALUES('" . $initial. "', '" . $lastname . "', '" . $country_id . "', NOW(),  '" . $friend . "', '" . $return . "', '" . $service . "',NULL)" or die("couldn't execute my query");
                    }

答案 1 :(得分:0)

这应该按预期工作。

尝试将列设置为int,如果这不起作用。

INSERT INTO table (val1, val2) VALUES('String Value', NULL);

或将默认列值设置为NULL。

答案 2 :(得分:0)

NULL值不能包含在'撇号'

考虑一下如何获得SQL:

INSERT INTO table_name VALUES ('null','');?

数据库可以理解为字符串

答案 3 :(得分:0)

只需将'NULL'值替换为NULL而不使用引号。

  $enter_feedback = "INSERT INTO feedback" . //(initial, surname, country_id, date, friend_score, return_score, service_score, comments)
                " VALUES('" . $initial. "', '" . $lastname . "', '" . $country_id . "', NOW(),  '" . $friend . "', '" . $return . "', '" . $service . "', NULL) " or die("couldn't execute my query");

一旦这样做并保存记录,当您通过PHPMYADMIN浏览时,您将在该字段的数据库列中看到NULL。请确保有问题的字段“comments”允许NULL。