在列中插入NULL?

时间:2010-11-04 17:05:45

标签: mysql

我正在试图弄清楚如何将NULL值插入到新插入行的列中。

我正在研究“帖子图标”,它会在帖子列表中显示一个小图标。图标使用表单中的RADIO按钮。默认情况下,它设置为No Icon。我想知道如何处理该单选按钮的值,使其为空?我尝试将值设置为NULL,但它只是将单词“NULL”插入数据库。

            $thread_sql = "
            INSERT INTO forum_threads (
                user_id,
                forum_id,
                thread_postdate,
                thread_lastpost,
                thread_title,
                thread_description,
                thread_icon
            ) VALUES (
                '$_SESSION[user_id]',
                '$_GET[f]',
                '$date',
                '$date',
                '$_POST[topictitle]',
                '$_POST[topicdescription]',
                '$_POST[posticon]'
            )
        ";
        $thread_query = @mysqli_query ($db_connect, $thread_sql);

3 个答案:

答案 0 :(得分:4)

使用MySQL:

insert into your_table (nulled_column) values (null);

如果您获得'NULL'字面值而不是null值,可能是因为您没有从客户端发出正确的命令(PHP,C#,Java程序)。您需要共享用于插入的代码,以获得更多帮助。

更新:

根据您最近编辑过的问题,当您插入NULL值时,只需删除''。如果您使用'',则会按照您的提及插入'NULL'个文字。

我还建议您在MySQL中使用PreparedStatements以避免SQL注入攻击。

答案 1 :(得分:1)

做这样的事情(PDO):

$stmt  = $db->prepare('INSERT INTO foo(bar) values (?);');
$stmt->execute(array($value=='NULL'? NULL,$value));

mysql

mysql_query('INSERT INTO foo(bar) 
   values ('.($value=='NULL'? 'NULL',"'".mysql_real_escape_string($value)."'").')';

答案 2 :(得分:-1)

这很有效。不得不使用IF

        if (isset($_POST['submit'])) {
        $thread_sql = "
            INSERT INTO forum_threads (
                user_id,
                forum_id,
                thread_postdate,
                thread_lastpost,
                thread_title,
                thread_description,
                thread_icon
            ) VALUES (
                '$_SESSION[user_id]',
                '$_GET[f]',
                '$date',
                '$date',
                '$_POST[topictitle]',
                '$_POST[topicdescription]',
                IF('$_POST[posticon]'='NULL',NULL,'$_POST[posticon]')
            )
        ";
        $thread_query = @mysqli_query ($db_connect, $thread_sql);
相关问题