This article mainly introduces how to insert multiple data records using an SQL statement in mysql, which is very efficient, but the principle is actually very simple. I hope it will help you if there is A data table:
Id name title addtime
To insert n data entries:
$time= time();$data = array( array( 'name'=>'name1','title'=>'title1','addtime'=>$time; ), array( 'name'=>'name2','title'=>'title2','addtime'=>$time; ), array( 'name'=>'name3','title'=>'title3','addtime'=>$time; ), ... array( 'name'=>'nameN','title'=>'titleN','addtime'=>$time; ), );
Previously, my idea was to construct multiple insert statements through data and call them cyclically. For example:
$sql1 = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ('name1','title1','".$time."')";$sql2 = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ('name2','title2','".$time."')";......$sqlN = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ('nameN','titleN','".$time."')";
After that, you can insert multiple SQL insert statements at a time:
$sql = "INSERT INTO `A`(`name`,`title`,`addtime`)VALUES ('name1','title1','".$time."'),";$sql .= "('name2','title2','".$time."'),";$sql .= "('name3','title3','".$time."'),";.....$sql .= "('nameN','titleN','".$time."')";
By separating multiple data with the ",", you can use one SQL operation to insert multiple data. in the previous Test, when the number of inserted data entries is 30, one insert is nearly nine times faster than multiple inserts of the same data. At the same time, because there is only one insert operation, it is similar to a transaction operation. if the insertion fails, all of them fail. if the insertion succeeds, all are successful, making data management more convenient. Therefore, if multiple data entries need to be inserted into the same table, try this method.
This is often the case when inserting multiple database records:
$b = 14;for($a=0;$a<100;$a++){ $sql = " INSERT INTO `roles` (`uid`,`rid`) VALUES (".$a.",".$b.")"; mysql_query($sql);}
However, this writing method is inefficient and requires multiple SQL statements to be executed. If you have used phpmyadmin to import data, you will find that the above statement can actually be written in this way.
INSERT INTO `roles` (`uid`,`rid`) VALUES (534,14),(535,14),(536,14),(537,14),(539,14)
So the original code can be rewritten as follows:
$b = 14;for($a=0;$a<100;$a++){ if($a==0) $sql = "INSERT INTO `roles` (`uid`,`rid`) VALUES (".$a.",".$b.")"; else $sql. = ",(".$a.",".$b.")";}mysql_query($sql);