1.4.4. INSERT

1.4.4.1. Building The Query

1.4.4.1.1. Into

Use the into() method to specify the table to insert into.

$insert->into('foo');

1.4.4.1.2. Columns

You can set a named placeholder and its corresponding bound value using the column() method.

// INSERT INTO foo (bar) VALUES (:bar)
$insert->column('bar', $bar_value);

Note that the PDO parameter type will automatically be set for strings, integers, floats, and nulls. If you want to set a PDO parameter type yourself, pass it as an optional third parameter.

// INSERT INTO foo (bar) VALUES (:bar);
$insert->column('bar', $bar_value, \PDO::PARAM_LOB);

You can set several placeholders and their corresponding values all at once by using the columns() method:

// INSERT INTO foo (bar) VALUES (:bar)
$insert->columns([
    'bar' => $bar_value,
    'baz' => $baz_value
]);

However, you will not be able to specify a particular PDO parameter type when doing do.

Bound values are automatically quoted and escaped; in some cases, this will be inappropriate, so you can use the raw() method to set column to an unquoted and unescaped expression.

// INSERT INTO foo (bar) VALUES (NOW())
$insert->raw('bar', 'NOW()');

1.4.4.1.3. RETURNING

Some databases (notably PostgreSQL) recognize a RETURNING clause. You can add one to the Insert using the returning() method, specifying columns as variadic arguments.

// INSERT ... RETURNING foo, bar, baz
$insert
    ->returning('foo')
    ->returning('bar', 'baz');

1.4.4.1.4. Flags

You can set flags recognized by your database server using the setFlag() method. For example, you can set a MySQL LOW_PRIORITY flag like so:

// INSERT LOW_PRIORITY INTO foo (bar) VALUES (:bar)
$insert
    ->into('foo')
    ->column('bar', $bar_value)
    ->setFlag('LOW_PRIORITY');

1.4.4.2. Performing The Query

Once you have built the query, call the perform() method to execute it and get back a PDOStatement.

$result = $insert->perform(); // : PDOStatement

1.4.4.2.1. Last Insert ID

If the database autoincrements a column while performing the query, you can get back that value using the getLastInsertId() method:

$id = $insert->getLastInsertId();

Note:

You can pass a sequence name as an optional parameter to getLastInsertId(); this may be required with PostgreSQL.