blob: 147158420a9642b1d899c3b75b7af4c168550624 (
plain)
1 Writing an Array to Sql Conversion Function
2 ===========================================
3 :author: Aaron Ball
4 :email: nullspoon@iohq.net
5
6 Lately I've been doing a lot of converting arrays from key-value pairs to SQL
7 insert statements. I've been doing it so much in fact that it became pretty
8 apparent I would need a toSql function to keep from duplicating this code. With
9 that, here's my function. Hopefully it comes in handy for some of you.
10
11 ----
12 private function toSql($KeysValues) {
13 // Parse from array to quoted csv
14 $keys=implode(',',array_keys($KeysValues));
15 $values='\''.implode('\',\'',array_values($KeysValues)).'\'';
16 return array($keys, $values);
17 }
18 ----
19
20 This spits out an array with a key string and a value string encased in single
21 quotes. To use this all you need is
22
23 ----
24 <?php
25 $data = toSql($KeysValuesArray);
26 $sql = 'INSERT INTO test_table ('.$data[0].') VALUES ('.$data[1].')';
27 ?>
28 ----
29
30
31 Category:MySQL
32 Category:PHP
33
34
35 // vim: set syntax=asciidoc:
|