im making a class to easy manage SQL commands. I created all CRUD and right now im trying make a new method called save ($ data, $ table).
“save” must Recognize if INSERT or UPDATE is a sentence.
I’m totally lost in this step, my brain does not sense a safe and effective way to recognize which of the two sentences is.
My first idea was to compare using the primary key …
value exists : update
value doesnt exists or empty : insert
But,this is a weak solution.For example, if a malicious user sends ID=5 in form, automatically overwrite the user with id 5.
I accept suggestions and solutions, Thanks!
Two parts to the answer:
the SQL you want is
INSERT(fields) VALUES() ON DUPLICATE KEY UPDATE…
the method to control is to send some other unique identifier, not the ID. In your table, have the primary key (auto increment) and also a “unique_id” random string md5()’d set as unique key in the table. Send the random string as the identifier. Then do the update based on that random string. If it doesn’t exist, it’ll create a new record and auto-increment a primary key.
I would go deeper than this to validate if you’re expecting a “new” or “update”, but this method appears to fit what you’re asking for.