Generate SQL Statement from Array
Like this blog? Consider exploring one of our sponsored banner ads...
I often have an array of key/val pairs that correspond to the database fields and values. A good example is from a form post, you groom the incoming variables you want and store them in a groomed array. If the names of the groomed keys are the same as the table fields, you can use this simple function to build your sql statement:
function sqlGen($table,$data){ $keys = $vals = ''; foreach ($data as $key => $val){ $keys .= "`".mysql_real_escape_string($key)."`,"; $vals .= "'".mysql_real_escape_string($val)."',"; } $sql = "INSERT INTO `$table` (".substr($keys,0,-1).") VALUES (".substr($vals,0,-1).")"; return $sql; }
About this entry
You’re currently reading “Generate SQL Statement from Array,” an entry on BRADINO
- Published:
- 3.25.07 / 6pm
- Category:
- PHP
- Tags:
No comments
Jump to comment form | comments rss [?]