replace()
The replace()
method inserts or replaces rows in a table based on the table's primary key or unique index. It uses a REPLACE INTO
SQL statement internally.
Signature:
public function replace(string $tableName, array $insertData): bool
Basic Usage – Comparison
$replace = [
'id' => 42,
'email' => 'updated.email@example.com',
'status' => 'active',
'updated_at' => $db->now()
];
$success = $db->replace('test_users', $replace);
$success = $db->replace('test_users', [
'id' => 42,
'email' => 'updated.email@example.com',
'status' => 'active',
'updated_at' => $db->now()
]);
Return Value
true
on successfalse
on failure (checkgetLastError()
)
Notes
replace()
overwrites existing rows matching unique or primary keys- If no matching row exists, it performs an insert
- Supports SQL expressions and special values like
$db->now()
- Use carefully to avoid unintended data loss
- Prepared statements protect against SQL injection