Search code examples
phpmysqlnullsql-insert

MySQL and PHP - insert NULL rather than empty string


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 entered I pass along an empty string as a value. How do I pass an explicit NULL value to MySQL (if empty)?

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  '$intLat', '$intLng')";
mysql_query($query);

Solution

  • If your variable already contains null, prepared statements will do it for you without any extra code

    $query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
              VALUES (?,?,?,?,?,?)";
    $data = [$notes, $id, $imageUploaded, $lat, $long, $intLat, $intLng];
    $conn->prepare($query)->execute($data);
    

    as simple as that.

    Any variable that contains a PHP null will be written as MySQL null. Not to mention this query is safe from SQL injection.

    If case you want to set a variable to null if it contains an empty string, here is how you can do it before running this query:

    $intLat = ($intLat === '') ? null : $intLat;