標籤:執行 family span array https important letter soft 資料庫
原文網址: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);}
php數組插入資料庫這個功能該怎麼實現