This article mainly introduces the simple implementation method of Yii framework batch insertion data extension class, involving Yii extension class and database related operation skills. Friends in need can refer to it
The example of this article tells the Yii framework batch Simple implementation method of inserting data extension class. Share it with everyone for your reference, the details are as follows:
MySQL INSERT statement allows inserting multiple rows of data, as shown below:
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
Then you need to implement batch insertion , the main task is to assemble the data into the above format in column order, which can be achieved using the sprintf and vsprintf functions.
The following is a simple example of a Yii extension class that implements batch insertion (supports VARCHAR type data):
<?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(); } }
The method of use is to add one by one through the add method data, and then call execute to execute.
The above is the detailed content of Implementation method of batch insertion class of data in Yii. For more information, please follow other related articles on the PHP Chinese website!