Set value to NULL in MySQL

前端 未结 9 1324
逝去的感伤
逝去的感伤 2020-11-30 01:17

I want a value to be set to NULL if nothing is put into the text box in the form I\'m submitting. How can I make this happen? I\'ve tried inserting \'NULL

相关标签:
9条回答
  • 2020-11-30 02:04

    You're probably quoting 'NULL'. NULL is a reserved word in MySQL, and can be inserted/updated without quotes:

    INSERT INTO user (name, something_optional) VALUES ("Joe", NULL);
    UPDATE user SET something_optional = NULL;
    
    0 讨论(0)
  • 2020-11-30 02:06

    The answers given here are good but i was still struggling to post NULL and not zero in mysql table.

    Finally i noted the problem was in the insert query that i was using

       $quantity= "NULL";
       $itemname = "TEST";
    

    So far so good.

    My insert query was bad.

       mysql_query("INSERT INTO products(quantity,itemname) 
       VALUES ('$quantity','$itemname')");
    

    I corrected query to read.

       mysql_query("INSERT INTO products(quantity,itemname) 
       VALUES ('".$quantity."','$itemname')");
    

    So the $quantity is outside of the main string. My sql table now accepted to record null quantity instead of 0

    0 讨论(0)
  • 2020-11-30 02:15
    if (($_POST['nullfield'] == 'NULL') || ($_POST['nullfield'] == '')) {
       $val = 'NULL';
    } else {
       $val = "'" . mysql_real_escape_string($_POST['nullfield']) . "'";
    }
    
    $sql = "INSERT INTO .... VALUES ($val)";
    

    if you put 'NULL' into your query, then you're just inserting a 4-character string. Without the quotes, NULL is the actual null value.

    0 讨论(0)
提交回复
热议问题