基本上我有这个数组,我想改成数据库查询
Array
(
[table] => menu
[fields] => Array
(
[mid] => menu_admin
[language] => EN
[name] => Admin
)
)
Array
(
[table] => user
[fields] => Array
(
[uid] => 1
[rid] => admin
[first_name] => Admin
[last_name] => Admin
[email] => contact@admin.com
[password] => xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
[date_register] => Zend_Db_Expr Object
(
[_expression:protected] => NOW()
)
[last_connexion] => NULL
[enable] => 1
)
)
依此类推......我想这样:
INSERT INTO `menu` (`mid`, `language`, `name`) VALUES
('menu_admin', 'EN', 'Admin');
INSERT INTO `user` (`uid`, `rid`, `first_name`, `last_name`, `email`, `password`, `date_register`, `last_connexion`, `enable`) VALUES
(1, 'admin', 'Admin', 'Admin', 'contact@admin.com', 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', '2014-02-27 15:33:45', '0000-00-00 00:00:00', 1);
这是我尝试的内容:
foreach ($query as $sql) {
$keys = rtrim(explode(", ", array_keys($sql['fields']), ",")); //<--Here
$fields = rtrim(explode(", ", $sql['fields']), ","); //<--And here
$sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $sql['table'], $fields, $keys);
}
var_dump($sql);
以下是错误:explode() expects parameter 2 to be string, array given
但我无法理解我是如何实现它的。对此有何帮助?谢谢。
答案 0 :(得分:2)
这是一个将从源数组构建SQL语句的函数:
function buildInsertSQL($array){
foreach($array as $key => $value){
if ($key == 'table'){
$table = $value;
}
if ($key == 'fields'){
$columns = array_keys($value);
$values = array_values($value);
}
}
$sql = "INSERT INTO `". $table . "` (".implode(", ", $columns).")";
$sql .= " VALUES ('".implode("', '", $values)."') ";
return $sql;
}
$test = array(
'table' => 'menu',
'fields' => array(
'mid' => 'menu_admin',
'language' => 'EN',
'name' => 'Admin'
)
);
$sql = buildInsertSQL($test);
echo $sql;
答案 1 :(得分:1)
// example code
foreach ($query as $sql)
{
$cols = array();
$vals = array();
foreach($sql['fields'] as $key => $val)
{
array_push($cols, "`". $key."`");
array_push($vals, "'". $val."'");
}
echo "INSERT INTO `".$sql['table']."` (".implode(',', $cols).") VALUES (".implode(',', $vals).")";
}