[英]Insert large amount of array data into DB
我有一个包含数万个数据的多维数组。 很多......数组的结构如下:
Array (
[0] => Array ( [0] => city [1] => code [2] => country )
[1] => Array ( [0] => city [1] => code [2] => country )
)
我想要做的是将数组值city,code和country插入到mysql数据库的表中。 我发现的帖子与我想要的完全匹配,但由于某种原因,它不能与我合作。 当我说它不工作时,我的意思是PHP甚至没有启动。 如果我删除下面的代码,该文件运行正常。 所以问题确实来自代码部分。 希望有人不介意帮助我。 先感谢您。 干杯。 渣。
//some code to build the array
//db_connect code
$sql = array();
foreach( $myarray as $row )
{
$sql[] = '("'.$row[0].'", "'.$row[1]).'","'.$row[2].'")';
}
mysql_query('INSERT INTO test (t_city, t_code, t_country) VALUES '.implode(',', $sql));
如前所述,构建sql
数组时的错误是一个多余的括号。 更改
$sql[] = '("'.$row[0].'", "'.$row[1]).'","'.$row[2].'")';
至
$sql[] = '("'.$row[0].'", "'.$row[1].'","'.$row[2].'")';
正如ashein在评论中指出的那样,查询长度受“max_allowed_paket”变量的限制。 如果查询大于此值,则会引发错误并关闭连接。
$ row [1]后面有一个方括号:)
使用此(删除括号):
$sql[] = '("'.$row[0].'", "'.$row[1].'","'.$row[2].'")';
您可以尝试将每个数组记录作为单独的sql-query插入。
foreach( $myarray as $row )
{
mysql_query('INSERT INTO test (t_city, t_code, t_country) VALUES ("'.$row[0].'", "'.$row[1]).'","'.$row[2].'");
}
但会有很多疑问
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
您希望通过一次提交多个值对而不是运行到限制中来动态构建此类查询。
所以你要做的是构建插入查询,同时迭代地迭代一行。 如果添加行将触发限制,则发送查询并重置查询:
# sample data
$data = array(
array('city1', 'code', 'country'),
array('city2', 'code', 'country'),
array('city3', 'code', 'country'),
array('city4', 'code', 'country'),
array('city5', 'code', 'country'),
array('city6', 'code', 'country'),
array('city7', 'code', 'country'),
);
$max_allowed_packet = 1048576; # mysql default value
$max_allowed_packet = 128; # for demonstration purposes
$sql = new SQLInsertQuery('INSERT INTO test (t_city, t_code, t_country) VALUES ', $max_allowed_packet);
foreach($data as $row) {
$sql->addRow($row);
}
$sql->query(); # manually query any potential left-over query.
此示例输出以下内容:
Running: INSERT INTO test (t_city, t_code, t_country) VALUES ('city1','code','country'),('city2','code','country');
Running: INSERT INTO test (t_city, t_code, t_country) VALUES ('city3','code','country'),('city4','code','country');
Running: INSERT INTO test (t_city, t_code, t_country) VALUES ('city5','code','country'),('city6','code','country');
Running: INSERT INTO test (t_city, t_code, t_country) VALUES ('city7','code','country');
您可能还想为运行的查询添加一个计数器,这样您就可以在循环和最终查询之后验证是否发送了一个查询(限制可能太低,因此根本不会发送任何查询 - 具体取决于您的数据 - 所以值得对这个边缘情况进行健全性检查。
我希望这个例子很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.