21.2.14

REPLACE instead of SELECT and then INSERT or UPDATE

It's nice that MySQL has the replace query so instead SELECTing to check if the data exists in the DB and than INSERTing or UPDATEing I just need to write one query.

So instead this:
$q = "SELECT id FROM table WHERE name = 'value' AND name2 = 'value2' LIMIT 1;";
$id = $database->get_one($q);
if ($id > 0) {
    $q = "UPDATE table SET name = 'value', name2 = 'value2' WHERE id = $id LIMIT 1;";
}
else {
    $q = "INSERT INTO table (name, name2) VALUES ('value', 'value2');";
}
$database->query($q);

I just query once
$q = "REPLACE INTO table (name, name2) VALUES ('value', 'value2');";
$database->query($q);


More info at
http://blogs.coldbuffer.com/inserting-or-updating-records-using-mysql-replace
https://dev.mysql.com/doc/refman/5.0/en/replace.html

No comments:

Post a Comment