Insert

The Insert class is used to build SQL INSERT statements.

Methods

addData(array $data)

Adds or replaces data in the insert dataset from an associative array.

Example:

use Staple\Query\Insert;

$insert = new Insert('users');
$insert->addData(['username' => 'jdoe', 'email' => 'jdoe@example.com']);

setDataColumn($column, $data, $literal)

Sets a specific column’s value. If $literal is true, the value is treated as raw SQL.

Example:

$insert->setDataColumn('created_at', 'NOW()', true);

setTable($table)

Sets the target table for the insert operation.

setPriority($priority)

Sets the insert priority (e.g., Insert::LOW, Insert::DELAYED, Insert::HIGH).

setIgnore($ignore)

Sets the IGNORE flag for the insert statement to skip errors on duplicate keys (MySQL/SQLite).

onDuplicateKeyUpdate($bool)

Enables or disables the ON DUPLICATE KEY UPDATE clause. Use setUpdateColumns() to specify which columns to update.

Example:

$insert->setUpdateColumns(['last_login']);
$insert->onDuplicateKeyUpdate();
// Result: ... ON DUPLICATE KEY UPDATE last_login=VALUES(last_login)

build()

Builds and returns the SQL string for the INSERT statement.

execute()

Executes the INSERT query and returns the statement object.

Example:

$insert->execute();
$newId = $insert->getInsertId();

getInsertId()

Returns the last inserted ID from the database connection.