挿入複数の列を介してphpのmysql配列
-
13-09-2019 - |
質問
私は過大規模なデータセットへのMySQLのテーブル経由でPHPを使用insertコマンドをやった場合にその可能性を挿入する約1000行時間によりクエリー以外の各要素の値をマイルの長い文字列を実行します。を使用していCodeIgniterの枠組みでその機能をご利用ください。
解決
組立一 INSERT
決算複数の列ではなく、あるMySQL一 INSERT
計算書です。
とはいえ、でんきに文字列を扱う問題はPHP、アルゴリズムの問題ではなく、言語です。基本的には大きな文字でも間に合わない不要なcopyingをご覧ください。主ることを避けるために連結した.最速かつ最もメモリを効率的に構築することが可能となる大型文字列などを挿入するための数百人の行ではの implode()
機能の配列を割りになります。
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
このアプローチの利点はないコピーおよび再コピーするSQL文んで組み立て各連結;代わりに、PHPはこの 一度 の implode()
ます。この 大きな 勝ちです。
場合がたくさんのカラムとして、非常に長く、きも内側のループ同じ使用 implode()
割り当てる値の条項の外側の配列になります。
他のヒント
複数の挿入/バッチ挿入は、現在のCodeIgniterでサポートされています。私は同じ問題を抱えていました。それは質問に答えるために非常に遅れているものの、それが誰かを助けます。この質問に答える理由です。
$data = array(
array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
),
array(
'title' => 'Another title' ,
'name' => 'Another Name' ,
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
あなたがmysqli_stmtクラスを使用して、一つの行を挿入するためのクエリを作成し、そのデータの配列を反復処理できました。ような何かます:
$stmt = $db->stmt_init();
$stmt->prepare("INSERT INTO mytbl (fld1, fld2, fld3, fld4) VALUES(?, ?, ?, ?)");
foreach($myarray as $row)
{
$stmt->bind_param('idsb', $row['fld1'], $row['fld2'], $row['fld3'], $row['fld4']);
$stmt->execute();
}
$stmt->close();
「idsb」はどこであなたは(int型、ダブル、文字列、BLOB)をバインドしているデータの種類です。
私は、これは古いクエリですけど、私はただ読んでいたと私は私が他の場所で見つけたものを追加しようと思いました。
PHP 5のmysqliのは、あなたが上記の回答の挿入時間をスピードアップすることができますいくつかの良い機能を備えたojbectです。
$mysqli->autocommit(FALSE);
$mysqli->multi_query($sqlCombined);
$mysqli->autocommit(TRUE);
多くの行を挿入するとき、セミコロンで区切られた多くのINSERTステートメントで、マルチクエリが処理するが大幅挿入をスピードアップするので、上述したように実行するか、または単にストリング(sqlCombined)を行い、その後、それをオフに自動コミットをオフにしますそれら細かいます。
(検索と挿入!)これは、誰かが時間を節約することができます願っています。
R
あなたはいつもMySQLのLOAD DATA
を使用することができます:
LOAD DATA LOCAL INFILE '/full/path/to/file/foo.csv' INTO TABLE `footable` FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n'
むしろINSERT
文の束を使用するよりも大量の挿入を行います。
さて、あなたは、1000回のクエリの呼び出しを実行する必要はありませんが、これを行うことは結構です。
$stmt= array( 'array of statements' );
$query= 'INSERT INTO yourtable (col1,col2,col3) VALUES ';
foreach( $stmt AS $k => $v ) {
$query.= '(' .$v. ')'; // NOTE: you'll have to change to suit
if ( $k !== sizeof($stmt)-1 ) $query.= ', ';
}
$r= mysql_query($query);
データソースによっては、配列を取り込むことfile()
を経由して配列にファイルを開いて内容をダンプするのと同じくらい簡単かもしれません。
$query= array();
foreach( $your_data as $row ) {
$query[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $query));
行うことができるので複数の方codeigniter例
第 によるループ
foreach($myarray as $row)
{
$data = array("first"=>$row->first,"second"=>$row->sec);
$this->db->insert('table_name',$data);
}
第 --Insertバッチ
$data = array(
array(
'first' => $myarray[0]['first'] ,
'second' => $myarray[0]['sec'],
),
array(
'first' => $myarray[1]['first'] ,
'second' => $myarray[1]['sec'],
),
);
$this->db->insert_batch('table_name', $data);
第三の道--複数の値のパス
$sql = array();
foreach( $myarray as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['first']).'", '.$row['sec'].')';
}
mysql_query('INSERT INTO table (first, second) VALUES '.implode(',', $sql));
では遅すぎな変化を対象としています。ここでの私の回答と同じです。
ご利用の場合CodeIgniterを利用することができinbuiltで定義されているメソッドquery_builderクラスです。
$this->db->insert_batch()
を挿入文字列に基づくデータの供給、運行を返します。いずれかを渡すことができる配列やオブジェクトの機能です。ここでは、どの配列:
$data = array(
array(
'title' => 'My title',
'name' => 'My Name',
'date' => 'My date'
),
array(
'title' => 'Another title',
'name' => 'Another Name',
'date' => 'Another date'
)
);
$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'), ('Another title', 'Another name', 'Another date')
最初のパラメータが含まれまでのテーブル名を連想配列の値です。
きの詳細についてquery_builder こちらの
私は次のように使用されるマルチラインを実行するクラスを作成している
$pdo->beginTransaction();
$pmi = new PDOMultiLineInserter($pdo, "foo", array("a","b","c","e"), 10);
$pmi->insertRow($data);
// ....
$pmi->insertRow($data);
$pmi->purgeRemainingInserts();
$pdo->commit();
次のようにクラスが定義される:
class PDOMultiLineInserter {
private $_purgeAtCount;
private $_bigInsertQuery, $_singleInsertQuery;
private $_currentlyInsertingRows = array();
private $_currentlyInsertingCount = 0;
private $_numberOfFields;
private $_error;
private $_insertCount = 0;
/**
* Create a PDOMultiLine Insert object.
*
* @param PDO $pdo The PDO connection
* @param type $tableName The table name
* @param type $fieldsAsArray An array of the fields being inserted
* @param type $bigInsertCount How many rows to collect before performing an insert.
*/
function __construct(PDO $pdo, $tableName, $fieldsAsArray, $bigInsertCount = 100) {
$this->_numberOfFields = count($fieldsAsArray);
$insertIntoPortion = "REPLACE INTO `$tableName` (`".implode("`,`", $fieldsAsArray)."`) VALUES";
$questionMarks = " (?".str_repeat(",?", $this->_numberOfFields - 1).")";
$this->_purgeAtCount = $bigInsertCount;
$this->_bigInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks.str_repeat(", ".$questionMarks, $bigInsertCount - 1));
$this->_singleInsertQuery = $pdo->prepare($insertIntoPortion.$questionMarks);
}
function insertRow($rowData) {
// @todo Compare speed
// $this->_currentlyInsertingRows = array_merge($this->_currentlyInsertingRows, $rowData);
foreach($rowData as $v) array_push($this->_currentlyInsertingRows, $v);
//
if (++$this->_currentlyInsertingCount == $this->_purgeAtCount) {
if ($this->_bigInsertQuery->execute($this->_currentlyInsertingRows) === FALSE) {
$this->_error = "Failed to perform a multi-insert (after {$this->_insertCount} inserts), the following errors occurred:".implode('<br/>', $this->_bigInsertQuery->errorInfo());
return false;
}
$this->_insertCount++;
$this->_currentlyInsertingCount = 0;
$this->_currentlyInsertingRows = array();
}
return true;
}
function purgeRemainingInserts() {
while ($this->_currentlyInsertingCount > 0) {
$singleInsertData = array();
// @todo Compare speed - http://www.evardsson.com/blog/2010/02/05/comparing-php-array_shift-to-array_pop/
// for ($i = 0; $i < $this->_numberOfFields; $i++) $singleInsertData[] = array_pop($this->_currentlyInsertingRows); array_reverse($singleInsertData);
for ($i = 0; $i < $this->_numberOfFields; $i++) array_unshift($singleInsertData, array_pop($this->_currentlyInsertingRows));
if ($this->_singleInsertQuery->execute($singleInsertData) === FALSE) {
$this->_error = "Failed to perform a small-insert (whilst purging the remaining rows; the following errors occurred:".implode('<br/>', $this->_singleInsertQuery->errorInfo());
return false;
}
$this->_currentlyInsertingCount--;
}
}
public function getError() {
return $this->_error;
}
}
データの複数行を挿入するためにCodeIgniterのインサートバッチを使用します。
$this->db->insert_batch('tabname',$data_array); // $data_array holds the value to be inserted
私はあなたたちは簡単に使用することができ、この簡単な関数を作成しました。あなたの挿入データ、データ配列($tbl)
に対してテーブル名($insertFieldsArr)
、テーブルフィールド($arr)
を渡す必要があります。
insert_batch('table',array('field1','field2'),$dataArray);
function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array();
foreach( $arr as $row ) {
$strVals='';
$cnt=0;
foreach($insertFieldsArr as $key=>$val){
if(is_array($row)){
$strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
}
else{
$strVals.="'".mysql_real_escape_string($row).'\',';
}
$cnt++;
}
$strVals=rtrim($strVals,',');
$sql[] = '('.$strVals.')';
}
$fields=implode(',',$insertFieldsArr);
mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}