INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
このようなクエリを動的に作成するには、一度に複数の値のペアを送信し、制限に達しないようにします。
それでは、挿入クエリを作成しながら、繰り返して1つの行を追加します。行を追加すると、上限をトリガーする場合は、クエリが送信され、クエリがリセットされます:
# 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');
Demo、Gist
あなたがしたいかもしれませんクエリを実行するためのカウンタを追加すると、ループの後で検証できます。すべてのクエリが送信された場合は最終的なクエリが有効になります(制限は低すぎるため、データは送信されません。健全性をチェックする価値があるrこのエッジケース)。
この例が役立ちますようにお願いします。
コードはきれいに見えます。 SQLクエリーの中に何千ものデータを埋め込むことはできません。 – seferov
コードが挿入されたときにPHPファイルが実行されないため、別のエラーが発生することがあります... – Marc
[PHPのクエリは "max_allowed_packet"によって制限されています...](http://stackoverflow.com/questions/ 5735150/php-max-insert-in-one-sql-query) – ashein