0

I have an ordering system from 1 to 6 (both inclusive), which the order number is assigned to a news in table featured by user's choice. When a user saves an order for a news, in the table featured is inserted a new row with these fields: id_news, id_user, id_category and order

What I am looking for is for a better syntax to check if there already is a news for client X with order Y.

Right now I'm doing each thing in a separate query, with these actions:

  1. User chooses to feature news 1241 to order number 3
  2. Script checks to see if there exists any news for client X with order number 3
  3. If exists, it deletes it
  4. Add the new featured news.

Anyway of making all that in less actions/code?

1 Answer 1

1

Use ON DUPLICATE KEY UPDATE.

Assuming (id_user,order) is a unique key, then you can just insert the new value and, if the order already exists, update it with the new id_news.

INSERT INTO `featured` VALUES (...) ON DUPLICATE KEY UPDATE `id_news`=VALUES(`id_news`)
Sign up to request clarification or add additional context in comments.

4 Comments

So that would change my id_news's order value with the new id_news?
Another way around it if (id_user, order) is not unique, you can run an update statement and check for affected rows, if no rows were affected, then you run the insert statement.
@Ateszki it's kinda the same thing as the response above, only some more php interaction. Thanks anyway, for your suggestion
indeed, it is almost the same, but it helps you if you don't have or don't want the unique index. You are welcome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.