There is such a code

$data = array('Cathy', '9 Dark and Twisty Road', 'Cardiff'); $STH = $DBH->prepare("INSERT INTO folks (name, addr, city) values (?, ?, ?)"); $STH->execute($data); 

Instead of VALUES dumps the $data array. Is there a method that transfers an array, not instead of VALUES but instead of attributes.

    1 answer 1

    You can go around and do this:

     $fields_array = array('name', 'addr', 'city'); $fields = implode(', ', $fields_array); $data = array('Cathy', '9 Dark and Twisty Road', 'Cardiff'); $STH = $DBH->prepare("INSERT INTO folks ($fields) values (?, ?, ?)"); $STH->execute($data); 

    The result is that we inserted fields into the query into which we then insert the data, I think the solution is not the best, but if it really is necessary, then I think this is the only way out.

    • one
      it is better not to make a clean implode . Imagine if the name of any column will be limit or values , etc. - Alexey Shimansky
    • @ Alexey Shimansky is unlikely that there may be a user interface. As a logic to build a query, when all the fields are determined right there and the right number to vary their number, this is a normal solution. - teran
    • @teran I did not speak about user-input. I talked about the fact that the developer can quite make himself in the database table with the name of the column LIMIT . Nobody forbids it and it is valid. However, when querying above, when the developer renders an array of fields and imposes - there will be an error - Alexey Shimansky
    • one
      @ Alexey Shimansky, as for me, that implode(',', [" 'limit' ", "field1"]) is also a clean implod) - teran
    • one
      In fact, you need to do something like this (although it looks scary): $arr = ['limit', 'field1', 'field2']; echo '`'.implode('`, `', $arr).'`'; $arr = ['limit', 'field1', 'field2']; echo '`'.implode('`, `', $arr).'`'; - Alexey Shimansky