Reputation: 742
I'm trying to figure out how I can insert a NULL value into a column of newly inserted row.
I'm working on "post icons" which will display a small icon for the thread on the thread list. The icons use RADIO buttons in the form. By default it is set to No Icon. I was wondering what to do for the value of that radio button to make it null? I tried setting value as NULL but it just inserts the word "NULL" into the database.
$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);
Upvotes: 0
Views: 709
Reputation: 181270
With MySQL:
insert into your_table (nulled_column) values (null);
If you are getting a 'NULL'
literal instead of a null
value, it's probably because you are not issuing the right command from your client (PHP, C#, Java program). You will need to share the code you are using for your insertion in order to get more help.
UPDATE:
According to your recently edited question, just get rid of the ''
when you are inserting NULL values. If you use ''
, then you'll get 'NULL'
literals inserted as you mentioned.
I would also suggest you use PreparedStatements
in MySQL in order to avoid SQL injection attacks.
Upvotes: 4
Reputation: 742
This works. Had to use an 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);
Upvotes: -2
Reputation: 70460
Just do something like this (PDO):
$stmt = $db->prepare('INSERT INTO foo(bar) values (?);');
$stmt->execute(array($value=='NULL'? NULL,$value));
Or with mysql
:
mysql_query('INSERT INTO foo(bar)
values ('.($value=='NULL'? 'NULL',"'".mysql_real_escape_string($value)."'").')';
Upvotes: 1