Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sqlite INSERT OR REPLACE INTO not working as expected

Tags:

php

sqlite

pdo

I'm trying to figure out what the problem is for hours :(

Table looks like this:

CREATE TABLE IF NOT EXISTS pages(
   id INTEGER PRIMARY KEY AUTOINCREMENT,
   title TEXT,
   parent INTEGER DEFAULT NULL,
   content TEXT,
   time INTEGER,
   FOREIGN KEY(category) REFERENCES categories(id) ON DELETE CASCADE,
   FOREIGN KEY(parent) REFERENCES pages(id) ON DELETE CASCADE,
   UNIQUE(title) ON CONFLICT REPLACE
)

The insert query:

INSERT OR REPLACE INTO pages (title, parent, content, time) VALUES (?, ?, ?, ?)

title should be unique, so if it founds a record with the same title it should replace it. It gets replaced, but the ID changes too! This is a problem because all other records that were having a parent field that was pointing to the old ID are getting removed :(

Why is this happening?

like image 652
thelolcat Avatar asked Dec 17 '25 17:12

thelolcat


1 Answers

Your ID is set to auto increment so when you replace something,the ID also changes.because replacing means deleting the old row and inserting a new one. I don't know if sqlite has INSERT ... ON DUPLICATE KEY UPDATE

like image 193
Mihai Avatar answered Dec 19 '25 16:12

Mihai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!