It is possible in the spirit of this:
/* $columns = array("foo", "bar"); $values = array("value foo", "value bar"); */ assert(count($columns) == count($values)); $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $table_name, implode(", ", $columns), implode(", ", array_map("mysql_real_escape_string", $values));
If it is necessary to do an insert on many rows, then a variation:
$sql_t = sprintf("INSERT INTO %s (%s) VALUES (%s)", $table_name, implode(", ", $columns), substr(str_repeat("%s,", count($columns)), 0, -1)); for ($all_values as $values) { $r = mysql_query(vsprintf($sql_t, array_map("mysql_real_escape_string", $values))); ... }
But this is necromancy. It is better to use PDO, in the spirit of
$q = $db->prepare("INSERT INTO foo (bar, baz) VALUES (:bar, :baz)"); $q->execute($values); // $values = array("bar" => ..., "baz" => ...);
For several rows, repeat the $q->execute()
call.
If there are a lot of similar requests, the same thing, only prepared statements should be generated dynamically. Very rough sketch:
/* $tables = array( "foos" => array("foo", "bar", "baz"), "eggs" => array("spam", "ham"), ); */ function prepend_colon($x) { return ":" . $x; } foreach($tables as $t => $c) { $q[$t] = $db->prepare(sprintf("INSERT INTO %s (%s) VALUES (%s)", $t, implode(",", $c), implode(",", array_map("prepend_colon", $c)))); }