针对 Sergiu 的函数 - implode() 会使事情变得容易得多……如下所示
<?php
function mysql_insert_assoc ($my_table, $my_array) {
$columns = array_keys($my_array);
$values = array_values($my_array);
$sql = "insert into `$my_table` ";
$sql .= "(\"" . implode("\", \"", $column_names) . "\")";
$sql .= " values ";
$sql .= "(" . implode(", ", $values) . ")";
$result = mysql_query($sql);
if ($result)
{
echo "The row was added sucessfully";
return true;
}
else
{
echo ("The row was not added<br>The error was" . mysql_error());
return false;
}
}
?>
因此,对此函数的调用如下所示
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));
向 mysql 发送以下 sql 查询
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")