"1","b"=>"2","c"=>"3");现在想执行数据库插入语句insert into admin(a,b,c) values(1,2,3);该怎么实现?"/> "1","b"=>"2","c"=>"3");现在想执行数据库插入语句insert into admin(a,b,c) values(1,2,3);该怎么实现?">

Home  >  Article  >  Backend Development  >  php数组插入数据库这个功能该怎么实现

php数组插入数据库这个功能该怎么实现

WBOY
WBOYOriginal
2016-06-06 20:23:551603browse

比如一个数组
$a=array("a"=>"1","b"=>"2","c"=>"3");
现在想执行数据库插入语句insert into admin(a,b,c) values(1,2,3);该怎么实现?

回复内容:

比如一个数组
$a=array("a"=>"1","b"=>"2","c"=>"3");
现在想执行数据库插入语句insert into admin(a,b,c) values(1,2,3);该怎么实现?

<code>$keys;
$value;
$keys = implode(",", array_keys($a));
$value = implode(",",array_values($a));

$db->query("insert into admin(".$keys.") values(".$value.")")</code>

你的问题可以简化为:

<code>$a=array("a"=>"1","b"=>"2","c"=>"3");
</code>

转化为 ('a','b','c') 和 (1,2,3)的过程,你想办法拼出这个字符串即可。方法有很多种,其中一种方法可以是:,

<code>$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.') ';







</code>

写个方法

<code>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);
}</code>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn