0

I have a MySQL statement that inserts some variables 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);
1
  • Are those fields integers? If so, you don't need to enclose them in quotes. You may wish to cast them to integers with intval() or (int), and then if they are null they will become 0. Commented Jan 6, 2011 at 21:17

2 Answers 2

2

Just use one insert, and if the variable is empty it will post to the database empty

Sign up to request clarification or add additional context in comments.

1 Comment

This is fine as long as those fields are defined as DEFAULT NULL. In the case of the statement above, in which everything appears to be a string, it works either way, too.
0

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 :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.