MySQL and PHP - insert NULL rather than empty string

后端 未结 9 1195
陌清茗
陌清茗 2020-11-28 03:34

I have a MySQL statement that inserts some variables into the database. I recently added 2 fields which are optional ($intLat, $intLng). Right now, if these values are not

相关标签:
9条回答
  • 2020-11-28 04:09

    For some reason, radhoo's solution wouldn't work for me. When I used the following expression:

    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
        (($val1=='')?"NULL":("'".$val1."'")) . ", ".
        (($val2=='')?"NULL":("'".$val2."'")) . 
        ")";
    

    'null' (with quotes) was inserted instead of null without quotes, making it a string instead of an integer. So I finally tried:

    $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
        (($val1=='')? :("'".$val1."'")) . ", ".
        (($val2=='')? :("'".$val2."'")) . 
        ")";
    

    The blank resulted in the correct null (unquoted) being inserted into the query.

    0 讨论(0)
  • 2020-11-28 04:11

    This works just fine for me:

    INSERT INTO table VALUES ('', NULLIF('$date',''))
    

    (first '' increments id field)

    0 讨论(0)
  • 2020-11-28 04:11

    your query can go as follows:

    $query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$lng', '" . ($lat == '')?NULL:$lat . "', '" . ($long == '')?NULL:$long . "')";
    mysql_query($query);
    
    0 讨论(0)
提交回复
热议问题