php数组插入数据库这个功能该怎么实现
原文网址:https://segmentfault.com/q/1010000004048449
比如一个数组
$a=array("a"=>"1","b"=>"2","c"=>"3");
现在想执行数据库插入语句insert into admin(a,b,c) values(1,2,3);该怎么实现?
1.
$keys;
$value;
$keys = implode(",", array_keys($a));
$value = implode(",",array_values($a));
$db->query("insert into admin(".$keys.") values(".$value.")")
2.
$a=array("a"=>"1","b"=>"2","c"=>"3");
$values=implode(',',array_values($a));
$keys="'".implode("','",array_keys($a))."'";
$sql='insert into admin';
$sql.='('.$keys.') ';
$sql.='values ';
$sql.='('.$values.') ';
3.
写个方法:
function insert($table,$data){
foreach($data as $k => $v){
$fields[] = $v;
$keys[] = $k;
}
$values = "('".implode("','", $fields)."')";
$column = "(`".implode("`,`", $keys)."`)";
$sql = "insert into {$table} {$column} values {$values}";
$this->query($sql);
}