insert()
The insert()
method inserts a single row into the specified table. It uses prepared statements for safety and supports special values like $db->now()
, $db->func()
, $db->not()
, and even subqueries.
Signature:
public function insert(string $table, array $data): int|false
Basic Usage – Comparison
$insert = [
'firstname' => 'Alice',
'lastname' => 'Example',
'email' => 'alice@example.com',
'username' => 'alice123',
'created_at' => $db->now()
];
$id = $db->insert('test_user', $insert);
$id = $db->insert('test_user', [
'firstname' => 'Alice',
'lastname' => 'Example',
'email' => 'alice@example.com',
'username' => 'alice123',
'created_at' => $db->now()
]);
Using SQL function via func()
$insert = [
'user_id' => 1,
'product_name' => 'Quantum Mug',
'price' => 42.50,
'status' => 'pending',
'order_date' => $db->func('CURDATE()')
];
$db->insert('test_orders', $insert);
$db->insert('test_orders', [
'user_id' => 1,
'product_name' => 'Quantum Mug',
'price' => 42.50,
'status' => 'pending',
'order_date' => $db->func('CURDATE()')
]);
Inserting with Subquery
$sub = $db->subQuery();
$sub->select('MAX(id)')->from('test_user');
$insert = [
'user_id' => $sub,
'product_name' => 'Delayed Order',
'status' => 'pending'
];
$db->insert('test_orders', $insert);
$sub = $db->subQuery();
$sub->select('MAX(id)')->from('test_user');
$db->insert('test_orders', [
'user_id' => $sub,
'product_name' => 'Delayed Order',
'status' => 'pending'
]);
Return Value
- If the insert was successful and an auto-increment ID was generated, this ID is returned as
int
- If no auto-increment value was generated but the insert was successful,
true
is returned - If no row was inserted (and no
ON DUPLICATE
was used),false
is returned - If an exception occurs,
false
is returned and logged (if debug is active)
Security Notes
- Prepared statements ensure safe value binding
- Table and column names are validated
- Subqueries and special values are checked internally