<?php
function generate_sql_query($query,$names,$values)
{
foreach ($names as $key => $value) {
// If the value exists within values.
if (isset($values[$value])) {
$dbvalues[]=(get_magic_quotes_gpc())?'\''. $values[$value] .'\'':'\''. addslashes($values[$value]) .'\'';
}
else {
return false;
}
$dbfields[] = (is_numeric($key))?$value:$key;
}
$dbfields = implode(',', $dbfields);
$dbvalues = implode(',', $dbvalues);
$sql = sprintf($query,$dbfields,$dbvalues);
return $sql;
}
$names = array('username','ccnumber_field' => 'ccnumber');
echo generate_sql_query('INSERT INTO tablename (%s) VALUES (%s)',$names,$_POST);
?>
Kindof a bit of both.
If the form name and the field name are the same, just use an integer key (in other words, don't make it associative). If they share different names, the key should be the databases field name and the value should be the forms name.
In my example, username is both the inputs name and fieldname, while ccnumber_field is the fieldname and ccnumber is the inputs name.
This, to me, seems more automatic and less lines of code to write (instead of writing addslashes manually for everyone and allows you to have field names and input names different.