PHP如何将多维数组中的数据批量插入数据库?

PHP将多维数组中的数据批量插入到数据库中,顾名思义,需要用循环来插入。

1.循环insert into 语句,逐渐查询

 1 <?php
 2     /* www.qSyz.net  */
 3     @mysql_connect('localhost','root') or exit('Failed to connect to MySQL server.');
 4     mysql_select_db('mysql');
 5     //$a是二维数组中的数据
 6     $a = array(
 7         0 => array(
 8             'id' => 123,
 9             'order' => 'xxxx'
10         ),
11         1 => array(
12             'id' => 456,
13             'order' => 'xxxx'
14         )
15     );
16     foreach($a as $ac){
17         $q = mysql_query("SELECT 1 FROM `表名` WHERE `order`='{$ac['order']}' LIMIT");
18         if(mysql_num_rows($q)===0){
19             mysql_query("INSERT INTO `表名` (`id`,`order`) VALUES('{$ac['id']}','{$ac['order']}')");
20         }
21     }
22     /* 当然,为了效率起见,应该考虑一次性插入多条数据,而不是每条数据执行一次MySQL查询. 那种写法要稍微复杂一点. */
23 ?>

如果数据量非常大的话,重复执行insert 语句显然不适合

 

 1 <?php
 2     $con = mysql_connect('localhost','root','root');
 3     
 4     if(!con){
 5         die('Could not connect: '.mysql_error());
 6     }
 7     mysql_select_db('mydatabase',$con);
 8     $arr = array(array('orderAmount'=>'52.9','orderCode'=>'130511RJQM1G','orderCreateTime'=>'2013-05-11 17:10:35'),array('orderAmount'=>'52.9','orderCode'=>'130511RJQM1G','orderCreateTime'=>'2013-05-11 17:11:16'));
 9     $valueStr = '';
10     foreach($arr as $v){
11         $valueStr .= "('',".$v['orderAmount'].",'".$v['orderCode']."','".$v['orderCreateTime']."'),";
12     } 
13     $valueStr = substr($valueStr,0,strlen($valueStr)-1);
14     
15     $insertSql = "INSERT into `order`(id,orderAmount,orderCode,orderCreateTime) values".$valueStr;
16 
17     mysql_query($insertSql);
18     
19 ?>

 

如果 需要判断数据库中已经存在数据时 不需要插入,可以在数据库字段中给定唯一,这样就不需要进行判断是否存在,只需要判断是否插入成功了。

1 for($i=0;$i<count($arr);$I++){
2      $re=$db ->insert($arr[$i]);
3      if(!$re)  continue;
4 }

 

以上还有一种解决方案,就是采用 insert ignore into 语句进行查询  http://blog.chinaunix.net/uid-20648927-id-1907272.html

 

posted @ 2017-02-14 16:39  小军的代码库  阅读(811)  评论(0编辑  收藏  举报