我是PHP的新手,不知道如何修改此函数的语法,以便它可以用于排除多个数组而不是只有一个。此代码自动插入表单中输入的每个值,而不必指定字段并排除一个数组(称为“提交”),并且是我在http://www.abeautifulsite.net/blog/2007/10/inserting-an-array-into-a-mysql-database-table/找到的稍微修改过的代码版本
我有几个要发布的数组,我想要从我的INSERT函数中排除它们,因为它们要么被单独处理和插入,要么在处理表单后触发用户重定向的位置。
function mysql_insert_array($db, $data, $exclude = array()) {
$fields = $values = array();
if( !is_array($exclude) ) $exclude = array($exclude);
foreach( array_keys($data) as $key ) {
if( !in_array($key, $exclude) ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
} else {
return array( "mysql_error" => mysql_error() );
}
}
$result = mysql_insert_array("db", $_POST, "submit");
答案 0 :(得分:1)
exclude参数可以是数组数组:
function mysql_insert_array($db, $data, $excludes = array()) {
$fields = $values = array();
if( !is_array($excludes) ) $excludes = array($excludes);
foreach($excludes as $exclude ) {
$data = array_diff_assoc($data, $exclude);
}
foreach( array_keys($data) as $key ) {
$fields[] = "`$key`";
$values[] = "'" . mysql_real_escape_string($data[$key]) . "'";
}
$fields = implode(",", $fields);
$values = implode(",", $values);
if( !mysql_query("INSERT INTO `$db` ($fields) VALUES ($values)") ) {
return array( "mysql_error" => mysql_error() );
}
}
然后,您可以像这样使用它:
$array1 = array('toto', 'titi', 'tata');
$array2 = array('submit', 'foo');
$parent_array = array ($array1, $array2);
$result = mysql_insert_array("db", $_POST, $parent_array);