MySQL and PHP - insert even if variable is blank?
I have a MySQL statement that inserts some varia开发者_如何学编程bles into the database. I recently added 2 fields which are optional ($intLat, $intLng), but I would like to include them in the insert statement if entered:
$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long',
'$intLat', '$intLng')";
mysql_query($query);
Just use one insert, and if the variable is empty it will post to the database empty
Disagree with Michael Stevens; if the values are optional, they should be NULL in the database. However, since you have them quoted, they will be inserted as empty strings. That would be bad from a data-sanity perspective.
So... how to do it? Spend a few moments writing (or finding...) a function that takes an associative array as input, and generates the query. Key ingredients: array_keys, implode and mysql_real_escape_string. The PHP Manual is littered with these :)
精彩评论