将PHP关联数组插入MySQL表

时间:2022-09-26 08:21:36

I have an array like this:

我有一个像这样的数组:

Array
(
    [0] => 08/21/13
    [1] => 08/21/13
    [2] => 08/21/13
    [3] => 08/21/13
    [4] => 08/21/13
    [5] => 08/21/13
)

How can I insert it to a MySQL database?

如何将其插入MySQL数据库?

2 个解决方案

#1


3  

PHP:

$query = "INSERT INTO tbl (your_date_column_name) VALUES "
         . "('" .implode("'),('", $your_array)."')";

MySQL Manual says:

MySQL手册说:

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

使用VALUES语法的INSERT语句可以插入多行。为此,请包含多个列值列表,每个列值都括在括号中并用逗号分隔。

So, SQL becomes,

所以,SQL成了,

INSERT INTO tbl (your_date_column_name) 
VALUES('08/21/13'),('08/21/13'),('08/21/13')
     ,('08/21/13'),('08/21/13'),('08/21/13');

#2


-1  

Using foreach
First store array to one variable

使用foreach First存储数组到一个变量

$a=array('08/21/13','08/21/13','08/21/13','08/21/13','08/21/13','08/21/13');
foreach($a as $key=>$value){
    $date=date_create($value);
    $date1=date_format($date,"Y-m-d");
    //Here Your Insert Query
    $query=mysql_query("INSERT INTO TABLENAME SET date='".$date1."'");
}

#1


3  

PHP:

$query = "INSERT INTO tbl (your_date_column_name) VALUES "
         . "('" .implode("'),('", $your_array)."')";

MySQL Manual says:

MySQL手册说:

INSERT statements that use VALUES syntax can insert multiple rows. To do this, include multiple lists of column values, each enclosed within parentheses and separated by commas.

使用VALUES语法的INSERT语句可以插入多行。为此,请包含多个列值列表,每个列值都括在括号中并用逗号分隔。

So, SQL becomes,

所以,SQL成了,

INSERT INTO tbl (your_date_column_name) 
VALUES('08/21/13'),('08/21/13'),('08/21/13')
     ,('08/21/13'),('08/21/13'),('08/21/13');

#2


-1  

Using foreach
First store array to one variable

使用foreach First存储数组到一个变量

$a=array('08/21/13','08/21/13','08/21/13','08/21/13','08/21/13','08/21/13');
foreach($a as $key=>$value){
    $date=date_create($value);
    $date1=date_format($date,"Y-m-d");
    //Here Your Insert Query
    $query=mysql_query("INSERT INTO TABLENAME SET date='".$date1."'");
}