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);
Advertisement
Answer
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)";