I’m building an application where users can add, edit and delete users from the database.
I’ve done the ‘View Users’ ( Select statement returning joined tables ) and the ‘Add Users’ ( Returns a form for user to fill in and INSERTS into database after validation of course )
But I’m having trouble with the ‘Edit Users’.
My Edit form is the SAME as the add form but the values for the text boxes are filled in with values from the database.
Upon submit, the logic checks for mismatches between the user input and the database values (So we know what we’re actually updating in the database)
So I end up with an array of all the values that need to be changed, example:
$values_to_update = array (
"telephone" => "07788991010"
"email_address" => "my_new_email_address@host.com"
);
The values in this array are dynamic and I need to thing of a way to dynamically update each field.
Also, the fields may also come from different tables.
I DON’T want to do:
if ( isset ( $values_to_update[ "telephone" ] ) )
$database->update("UPDATE users SET telephone = '{$values_to_update[ "telephone" ]}' WHERE user_id = $user_id");
else if ( isset ( $values_to_update[ "email_address" ] ) )
$database->update("UPDATE authentication SET email_address = '{$values_to_update[ "email_address" ]}' WHERE user_id = $user_id");
else if ( /* ... */)
// etc etc etc
Does anybody have any ideas of a better way I could do this?
I was thinking maybe I could use one HUGE update statement uses the same select statment that fetches the data. but i dont know how this would work.
Is it a standard practise for applications to store an array of fields to tables for dynamic query generation?
A clean way I’ve found of doing this in PDO-style ORM mappers (which is also used in Zend Framework):
Usually this amounts to writing a single
savemethod for each model. You could extend this inUPDATEsituations by keeping a copy of the originally-retrieved model, so that you only update the columns that have changed, however I don’t see any huge overhead by updating all columns.