PHP Classes

File: src/query/BatchNamedInsertQuery.php

Recommend this page to a friend!
  Classes of Vitaly   Queasy DB   src/query/BatchNamedInsertQuery.php   Download  
File: src/query/BatchNamedInsertQuery.php
Role: Class source
Content type: text/plain
Description: Class source
Class: Queasy DB
Execute queries by accessing class variables
Author: By
Last change:
Date: 3 years ago
Size: 1,522 bytes
 

Contents

Class file image Download
<?php

namespace queasy\db\query;

use
queasy\db\DbException;

class
BatchNamedInsertQuery extends TableQuery
{
   
/**
     * Execute multiple rows INSERT query using key-value arrays or objects.
     *
     * @param array $params Query parameters (array of key-value arrays or objects)
     *
     * @return int Number of inserted records
     *
     * @throws DbException On error
     */
   
public function run(array $params = array(), array $options = array())
    {
        if (!
count($params)) {
            throw new
DbException('Query parameters are empty.');
        }

       
$columnNames = array_keys($params[0]);
       
$columnsString = '`' . implode('`, `', $columnNames) . '`';

       
$paramsString = '';
       
$values = array();
       
$counter = 0;
        foreach (
$params as $row) {
           
$rowParams = array();
           
$columnIndex = 0;
            foreach (
$row as $value) {
               
$rowParams[] = $paramName = ':' . $columnNames[$columnIndex] . $counter;
               
$values[$paramName] = $value;
               
$columnIndex++;
            }

           
$paramsString .= '(' . implode(', ', $rowParams) . '), ';

           
$counter++;
        }
       
$paramsString = rtrim($paramsString, ', ');

       
$sql = sprintf('
            INSERT INTO `%s` (%s)
            VALUES %s'
,
           
$this->tableName(),
           
$columnsString,
           
$paramsString
       
);

       
$this->setSql($sql);

        return
parent::run($values, $options);
    }
}