"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 > Backend Development > PHP Tutorial > php数组插入数据库这个功能该怎么实现

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

WBOY
Release: 2016-06-06 20:23:55
Original
1671 people have browsed it

比如一个数组
$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>
Copy after login

你的问题可以简化为:

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

转化为 ('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>
Copy after login

写个方法

<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>
Copy after login
Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template