php教程

超轻量级php框架startmvc

YII框架批量插入数据的方法

更新时间:2020-03-18 18:26:23 作者:startmvc
本文实例讲述了YII框架批量插入数据的方法。分享给大家供大家参考,具体如下:publicfuncti

本文实例讲述了YII框架批量插入数据的方法。分享给大家供大家参考,具体如下:


public function insertSeveral($table, $array_columns)
{
 $sql = '';
 $params = array();
 $i = 0;
 foreach ($array_columns as $columns) {
 $names = array();
 $placeholders = array();
 foreach ($columns as $name => $value) {
 if (!$i) {
 $names[] = $this->_connection->quoteColumnName($name);
 }
 if ($value instanceof CDbExpression) {
 $placeholders[] = $value->expression;
 foreach ($value->params as $n => $v)
 $params[$n] = $v;
 } else {
 $placeholders[] = ':' . $name . $i;
 $params[':' . $name . $i] = $value;
 }
 }
 if (!$i) {
 $sql = 'INSERT INTO ' . $this->_connection->quoteTableName($table)
 . ' (' . implode(', ', $names) . ') VALUES ('
 . implode(', ', $placeholders) . ')';
 } else {
 $sql .= ',(' . implode(', ', $placeholders) . ')';
 }
 $i++;
 }
 return $this->setText($sql)->execute($params);
}
$rows = array(
 array('id' => 1, 'name' => 'John'),
 array('id' => 2, 'name' => 'Mark')
);
$command = Yii::app()->db->createCommand();
$command->insertSeveral('users', $rows);

YII 批量 插入数据