![](/img/trans.png)
[英]How to insert multiple records to database in Codeigneitor at same time
[英]How do you insert multiple records into a table at the same time?
我有兩張表Accommodation
和Facility
,它們以多對多的關系與第三張表Accommodation_facility
連接。
使用 Yii,如何在Accomodation_facility
表中插入多條數據記錄?
使用循環插入非常慢。 假設您有 5000 行要插入,這樣大約需要 6 分鍾(每條記錄單獨插入)。 最好使用單個查詢插入數據:
$values = '(null, "your string"), (null, "next string"), (null, "third string")';
$sql = 'INSERT INTO table_data (id, data) VALUES ' . $values;
$command = Yii::app()->db->createCommand($sql);
$command->execute();
這將花費 1/10 的時間。
您最好使用 bindParam 來防止 SQL 注入。 我不知道這是否是最好的方法,但我正在這樣做:
$values = array(array(1,2),array(3,4),array(5,6),);
$nbValues = count($values);
$sql = 'INSERT INTO table_name (col_name1, col_name2) VALUES ';
for ($i=0; $i < $nbValues; $i++) {
$sql .= '(:col1_'.$i.', :col2_'.$i.')';
if ($i !== ($nbValues-1))
$sql .= ',';
}
$command = Yii::app()->db->createCommand($sql);
for ($i=0; $i < $nbValues; $i++) {
$command->bindParam(':col1_'.$i, $values[$i][0], PDO::PARAM_INT);
$command->bindParam(':col2_'.$i, $values[$i][1], PDO::PARAM_INT);
}
$command->execute();
希望這可以幫助 !
//only for 1.1.14
$builder = Yii::app()->db->schema->commandBuilder;
$command=$builder->createMultipleInsertCommand('tbl_post', array(
array('title' => 'record 1', 'text' => 'text1'),
array('title' => 'record 2', 'text' => 'text2'),
));
$command->execute();
http://www.yiiframework.com/news/72/yii-1-1-14-release-candidate-is-available/
foreach($facilities as $facility)
{
$model = new Model;
$model->attributes = $facility // or $model->column = $facility
if ($model->validate())
$model->save()
}
由於您的問題被標記為“yii”,我猜您正在使用 Yii 框架。 在文檔中查看 Active Records - http://www.yiiframework.com/doc/guide/1.1/en/database.ar
按照文檔為您的表格設置 AR 類,並在您提交復選框列表時簡單地遍歷您發布的數據。 在此循環中,您為要插入數據的表創建、填充和保存 AR 對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.