Lately I’ve been doing a lot of converting arrays from key-value pairs to SQL insert statements. I’ve been doing it so much in fact that it became pretty apparent I would need a toSql function to keep from duplicating this code. With that, here’s my function. Hopefully it comes in handy for some of you.

private function toSql($KeysValues) {
  // Parse from array to quoted csv
  return array($keys, $values);

This spits out an array with a key string and a value string encased in single quotes. To use this all you need is

$data = toSql($KeysValuesArray);
$sql = 'INSERT INTO test_table ('.$data[0].') VALUES ('.$data[1].')';

Category:MySQL Category:PHP