How to Implement the php array database insertion function

Source: Internet
Author: User
For example, an array $ aarray (& quot; a & quot; & amp; gt; & quot; 1 & quot;, & quot; B & quot; & amp; gt; & quot; 2 & quot;, & quot; c & quot; & amp; gt; & quot; 3 & quot;); now you want to execute the database insert statement insertintoadmin (, b, c) values (, 3); how to implement it? For example, an array
$ A = array ("a" => "1", "B" => "2", "c" => "3 ");
Now I want to execute the database insert statement insert into admin (a, B, c) values (, 3); how can I implement it?

Reply content:

For example, an array
$ A = array ("a" => "1", "B" => "2", "c" => "3 ");
Now I want to execute the database insert statement insert into admin (a, B, c) values (, 3); how can I implement it?

$keys;$value;$keys = implode(",", array_keys($a));$value = implode(",",array_values($a));$db->query("insert into admin(".$keys.") values(".$value.")")

Your problem can be simplified:

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

The process of converting to ('A', 'B', 'C') and (, 3). You just need to spell out this string. There are many methods, one of which can be :,

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

Write Method

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);}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.