Yii框架批量插入數(shù)據(jù)擴展類的簡單實現(xiàn)方法
本文實例講述了Yii框架批量插入數(shù)據(jù)擴展類的簡單實現(xiàn)方法。分享給大家供大家參考,具體如下:
MySQL INSERT語句允許插入多行數(shù)據(jù),如下所示:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
那么要實現(xiàn)批量插入,主要的任務(wù)就是按照列順序,把數(shù)據(jù)組裝成上述格式即可,可以使用sprintf和vsprintf函數(shù)來實現(xiàn)。
下面是一個實現(xiàn)批量插入的Yii擴展類的簡單示例(支持VARCHAR類型數(shù)據(jù)):
<?php
/**
* class for sql batch insert
*/
class CDbBICommand extends CDbCommand{
/** @var CActiveRecord $class */
private $class;
/** @var string $insert_tpl */
private $insert_tpl = "insert into %s(%s) ";
/** @var string $value_tpl */
private $value_tpl = "(%s)";
/** @var string $query */
public $query;
/** @var CDbColumnSchema[] $columns */
private $columns;
/** @var boolean $fresh */
private $fresh;
/** @param CActiveRecord $class
* @param CDbConnection $db
*/
public function __construct($class,$db){
$this->class = $class;
$this->createtpl();
parent::_construct($db);
}
private function createtpl(){
$this->fresh = true;
$value_tpl = "";
$columns_string = "";
$this->columns = $this->class->getMetaData()->tableSchema->columns;
$counter = 0;
foreach($this->columns as $column){
/** @var CDbColumnSchema $column */
if($column->autoIncrement){
$value_tpl .= "0";
}else{
$value_tpl .= "\"%s\"";
}
$columns_string .= $column->name;
$counter ++;
if($counter != sizeof($this->columns)){
$columns_string .= ", ";
$value_tpl .= ", ";
}
}
$this->insert_tpl = sprintf($this->insert_tpl, $this->class->tableName(), $columns_string);
$this->value_tpl = sprintf($this->value_tpl, $value_tpl);
}
/**
* @param CActiveRecord $record
*/
public function add($record){
$values = array();
$i = 0;
foreach($this->columns as $column){
if($column->autoIncrement){
continue;
}
$values[$i] = $this->class->{$column->name};
$i ++;
}
if(!$this->fresh){
$this->query .= ",";
}else{
$this->query = "values";
}
$this->fresh = false;
$this->query .= vsprintf($this->value_tpl, $values);
return true;
}
public function execute(){
$this->setText($this->insert_tpl." ".$this->query);
return parent::execute();
}
}
使用方法是通過add方法逐個加入數(shù)據(jù),然后調(diào)用execute執(zhí)行。
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP框架實現(xiàn)WebSocket在線聊天通訊系統(tǒng)
這篇文章主要介紹了PHP框架結(jié)合實現(xiàn)WebSocket在線聊天通訊系統(tǒng),非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11
將博客園(cnblogs.com)數(shù)據(jù)導(dǎo)入到wordpress的代碼
博客園限制太多,于是決定從博客園(cnblogs)更換自己個人的博客。WORDPRESS口碑還不錯,于是決定用用看。之前發(fā)的數(shù)百篇日志需要導(dǎo)入過來,在網(wǎng)上搜了一會,發(fā)現(xiàn)沒有這個插件,無奈只能自己寫一個2013-01-01
destoon安裝出現(xiàn)Internal Server Error的解決方法
這篇文章主要介紹了destoon安裝出現(xiàn)Internal Server Error的解決方法,需要的朋友可以參考下2014-06-06
laravel 實現(xiàn)關(guān)閉CSRF(全部關(guān)閉、部分關(guān)閉)
今天小編就為大家分享一篇laravel 實現(xiàn)關(guān)閉CSRF(全部關(guān)閉、部分關(guān)閉),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-10-10

