Alex
Alex

Reputation: 7688

php mysql check existing syntax

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?

Upvotes: 0

Views: 79

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

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`)

Upvotes: 1

Related Questions