0

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.

3
  • Use ORM such as RedBean Commented Apr 8, 2018 at 4:34
  • Are both examples pseudocode, or real? Both seem susceptible to SQL injections, and VALUES ( `$entry->mail2` ) is invalid. Commented Apr 8, 2018 at 4:45
  • $entry is created beforehand in php and performs checks and escapes. due to number of security and validity check its in whole new file. the first example is real code, string in query(""). the second is just pseudocode to show what i mean. Commented Apr 8, 2018 at 5:10

1 Answer 1

2

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)) .
   "')";
Sign up to request clarification or add additional context in comments.

1 Comment

thanks. i hoped for some kind of auto function, but this is simple enough and i need to return get_object_vars($entry) for other functions anyway.

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.