This refactor seems workable in my head, but I’d like someone to check my logic:
Current process:
if (item == new) {
INSERT INTO basic_table
$itemUID = get last insert ID // item's UID
INSERT INTO another_table // more stuff
INSERT INTO another_table2 // more stuff
INSERT INTO another_table3 // more stuff
} else {
$itemUID = $_POST['uid']
UPDATE basic_table
REPLACE INTO another_table // more stuff
REPLACE INTO another_table2 // more stuff
REPLACE INTO another_table3 // more stuff
}
(note – REPLACE INTO is used for existing items because they may or may not have entries in all the tables, depending on their initial configuration)
It occurred to me that since all the follow-on queries are identical except for INSERT INTO // REPLACE INTO, I should be able to refactor as:
if (item == new) {
INSERT INTO basic_table
$itemUID = get last insert ID // item's UID
} else {
$itemUID = $_POST['uid']
UPDATE basic_table
}
REPLACE INTO another_table // more stuff
REPLACE INTO another_table2 // more stuff
REPLACE INTO another_table3 // more stuff
Considering that I’m using PDO and each of those queries has lots of parameters, this would save a crapload of space.
But I wanted to post it here first, to make sure I’m not overlooking something.
Would this refactoring produce the same result?
If you don’t care about the primary key changing, use
REPLACE. If the key needs to remain consistent, as in, if it has been mapped to other tables, continue to useINSERTandUPDATE.REPLACEdeletes and re-inserts so if your primary key is anauto_incrementfield it will change to the new increment value.