It would be nice to have functions that convert associative arrays to SQL queries. Such a function will save our time from building queries. The functions take two main parameters, the name of the table and the data to be inserted in associative array like this:
$data = array(
'name' => 'dede',
'email' => 'dede@gmail.com',
'city' => 'surabaya',
'age' => 21
);
The array then converted to SQL string:
INSERT INTO members (name, email, city, age)
VALUES ('dede', 'dede@gmail.com', 'surabaya', '21');
The function is simple. First we get the column names using array_keys(), and get the values using array_values(). Both arrays are converted to strings and joined to build the complete SQL string.
Listing 1: Build SQL INSERT
The function to generate the SQL for update is slightly different. In this function, each pairs of array elements is converted to "key='name'". An additional parameter is added for the WHERE clause.
Listing 2: Build SQL UPDATE
We've got functions to build the SQL for INSERT and UPDATE. Another function for data validation would be perfect.
The validation function takes two arguments. One argument is the data to be inserted, and the second argument is the regular expression for each column. For the example above, the regular expression would be something like this:
$regex = array(
'name' => "^[\\w.]+$",
'email' => "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*"
. "@[a-z0-9-]+(\\.[a-z0-9-]+)*\\.([a-z]{2,4})$",
'city' => "^[\\w]+$",
'age' => "^[0-9]{1,2}$"
);
And here's the data validation function:
Listing 3: Data validation
Put all of the functions above in one file, and make sure that the functions work.
Listing 4: All in one
Giuseppe Vigo on Nov 7, 2008:
ferdy on Feb 1, 2009:
Julian Davchev on Feb 15, 2009:
rex on Jun 28, 2010:
| ICQ | 489571630 |
| Skype | dede_bl4ckheart |
| Yahoo | dede_bl4ckheart |
| nashruddin.amin |
Alex on Aug 17, 2008:
Keep up the good work!