yii\db\QueryBuilder::insert PHP Method

insert() public method

For example, php $sql = $queryBuilder->insert('user', [ 'name' => 'Sam', 'age' => 30, ], $params); The method will properly escape the table and column names.
public insert ( string $table, array $columns, array &$params ) : string
$table string the table that new rows will be inserted into.
$columns array the column data (name => value) to be inserted into the table.
$params array the binding parameters that will be generated by this method. They should be bound to the DB command later.
return string the INSERT SQL
    public function insert($table, $columns, &$params)
    {
        $schema = $this->db->getSchema();
        if (($tableSchema = $schema->getTableSchema($table)) !== null) {
            $columnSchemas = $tableSchema->columns;
        } else {
            $columnSchemas = [];
        }
        $names = [];
        $placeholders = [];
        foreach ($columns as $name => $value) {
            $names[] = $schema->quoteColumnName($name);
            if ($value instanceof Expression) {
                $placeholders[] = $value->expression;
                foreach ($value->params as $n => $v) {
                    $params[$n] = $v;
                }
            } else {
                $phName = self::PARAM_PREFIX . count($params);
                $placeholders[] = $phName;
                $params[$phName] = !is_array($value) && isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
            }
        }
        return 'INSERT INTO ' . $schema->quoteTableName($table) . (!empty($names) ? ' (' . implode(', ', $names) . ')' : '') . (!empty($placeholders) ? ' VALUES (' . implode(', ', $placeholders) . ')' : ' DEFAULT VALUES');
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * @inheritdoc
  */
 public function insert($table, $columns, &$params)
 {
     $schema = $this->db->getSchema();
     if (($tableSchema = $schema->getTableSchema($table)) !== null) {
         $columnSchemas = $tableSchema->columns;
     } else {
         $columnSchemas = [];
     }
     //Empty insert
     if (empty($columns) && !empty($columnSchemas)) {
         $columns = [];
         foreach ($columnSchemas as $columnSchema) {
             if (!$columnSchema->autoIncrement) {
                 $columns[$columnSchema->name] = $columnSchema->defaultValue;
             }
         }
     }
     foreach ($columns as $name => $value) {
         if ($value instanceof Expression) {
             $columns[$name] = $this->convertExpression($value);
         } elseif (isset($columnSchemas[$name]) && in_array($columnSchemas[$name]->type, [Schema::TYPE_TEXT, Schema::TYPE_BINARY])) {
             $columns[$name] = [$value, \PDO::PARAM_LOB];
         }
     }
     return parent::insert($table, $columns, $params);
 }
All Usage Examples Of yii\db\QueryBuilder::insert