Reputation: 61
Please, I've got a table in an array I want to update with object with matching schema in php. query:
REPLACE INTO entries ( mail, name, gender, age, ip, t, code, v, ansvers )
VALUES ( '$entry->mail', '$entry->name', '$entry->gender', '$entry->age', '$entry->ip', '$entry->t', '$entry->code', '$entry->v', '$entry->ansvers' )
I'd like to know if there is any simple way to specify variables without having to create query string using loop and retrieving object/array variable keys or typing everything manually like this.
for example, if I rename $entry->mail
to $entry->mail2
then query will do:
REPLACE INTO entries ( mail2 ) VALUES ( `$entry->mail2` )
if needed, $entry can be changed to any data structure.
thanks.
Upvotes: 0
Views: 1299
Reputation: 147196
If there is truly a 1:1 correspondence from the object to the table you could do this to generate the query:
$query = "REPLACE INTO entries (" .
implode(',', array_keys(get_object_vars($entry))) .
") VALUES ('" .
implode("','", get_object_vars($entry)) .
"')";
Upvotes: 2