Build insert query from array MySQL and PHP
Try this:
function addUser($usrData) {
$count = 0;
$fields = '';
foreach($usrData as $col => $val) {
if ($count++ != 0) $fields .= ', ';
$col = mysql_real_escape_string($col);
$val = mysql_real_escape_string($val);
$fields .= "`$col` = $val";
}
$query = "INSERT INTO `myTable` SET $fields;";
}
EDIT:
Oops ! forgot quotation around VALUES( ), removing the old code
$query = "INSERT INTO `mytable` ( ".
mysql_real_escape_string(implode(' , ',array_keys( $userData))).
") VALUES ( '".
mysql_real_escape_string(implode("' , '", $userData)).
"' )";
Elegant solution:
function create_insert_query($tablename, $array) {
$key = array_keys($array);
$val = array_values($array);
//sanitation needed!
$query = "INSERT INTO $tablename (" . implode(', ', $key) . ") "
. "VALUES ('" . implode("', '", $val) . "')";
return($query);
}