I need to know the proper way of doing this. I have a form where someone can fill in 3 different inputs to update their data.
they can leave one blank if they want and just update the other two or just one. Whatever.
so if i update as:
mysql_query("UPDATE table SET field1=input AND field2=BLANK AND filed3=input WHERE ID=123);
will it leave the blank fields unchanged? just skip over them? or will it replace the field with an empty string/blank field?
If this is the wrong way, what is the correct method? Thank You!
It will replace them with blank values. The correct way to do it is not to put those items in the query at all:
if (empty($field1) && empty($field2) && empty($field3) {
// show error message, nothing to do
return;
}
$updates = array();
if (!empty($field1))
$updates[] = 'field1="'.mysql_real_escape_string($field1).'"';
if (!empty($field2))
$updates[] = 'field2="'.mysql_real_escape_string($field2).'"';
if (!empty($field3))
$updates[] = 'field3="'.mysql_real_escape_string($field3).'"';
$updates = implode(', ', $updates);
mysql_query("UPDATE table SET $updates WHERE ID=123");
Obviously it would be cleaner to put the changes in an associative array or object, and then loop through them.
The following UPDATE
statement should leave the fields unchanged if the user uses ''
as their input, otherwise, it will use the input given to update the field.
UPDATE table
SET field1 = CASE
WHEN input = '' THEN field1
ELSE input
END
, field2 = CASE
WHEN input2 = '' THEN field2
ELSE input2
END
, field3 = CASE
WHEN input3 = '' THEN field3
ELSE input3
END
WHERE ID = 123
This is done with the CASE statement. The WHEN
conditions check to see what the input it, and if it is ''
(omitted basically) it will use the current value of field1 to update field1 with, basically leaving it unchanged. If there is a value, it will use that new value instead.
If you do not wish to update a certain field you will have to remove the field from your UPDATE
statement.
UPDATE table
SET field1=input AND filed3=input
WHERE ID=123