MySQL and PHP - insert NULL rather than empty string

后端 未结 9 1194
陌清茗
陌清茗 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 03:45

    Check the variables before building the query, if they are empty, change them to the string NULL

    0 讨论(0)
  • 2020-11-28 03:46

    To pass a NULL to MySQL, you do just that.

    INSERT INTO table (field,field2) VALUES (NULL,3)
    

    So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

    $intLat = !empty($intLat) ? "'$intLat'" : "NULL";
    $intLng = !empty($intLng) ? "'$intLng'" : "NULL";
    
    $query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
              VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                      $intLat, $intLng)";
    
    0 讨论(0)
  • 2020-11-28 03:50

    If you don't pass values, you'll get nulls for defaults.

    But you can just pass the word NULL without quotes.

    0 讨论(0)
  • 2020-11-28 03:55

    All you have to do is: $variable =NULL; // and pass it in the insert query. This will store the value as NULL in mysql db

    0 讨论(0)
  • 2020-11-28 03:59

    you can do it for example with

    UPDATE `table` SET `date`='', `newdate`=NULL WHERE id='$id'
    
    0 讨论(0)
  • 2020-11-28 04:07

    Normally, you add regular values to mySQL, from PHP like this:

    function addValues($val1, $val2) {
        db_open(); // just some code ot open the DB 
        $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES ('$val1', '$val2')";
        $result = mysql_query($query);
        db_close(); // just some code to close the DB
    }
    

    When your values are empty/null ($val1=="" or $val1==NULL), and you want NULL to be added to SQL and not 0 or empty string, to the following:

    function addValues($val1, $val2) {
        db_open(); // just some code ot open the DB 
        $query = "INSERT INTO uradmonitor (db_value1, db_value2) VALUES (".
            (($val1=='')?"NULL":("'".$val1."'")) . ", ".
            (($val2=='')?"NULL":("'".$val2."'")) . 
            ")";
        $result = mysql_query($query);
        db_close(); // just some code to close the DB
    }
    

    Note that null must be added as "NULL" and not as "'NULL'" . The non-null values must be added as "'".$val1."'", etc.

    Hope this helps, I just had to use this for some hardware data loggers, some of them collecting temperature and radiation, others only radiation. For those without the temperature sensor I needed NULL and not 0, for obvious reasons ( 0 is an accepted temperature value also).

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