1
UPDATE userpostratings SET rating = $rating WHERE postID = 8

If a there isnt a row in userpostratings with postID = 8 i wanna INSERT instead. Could this be done with sql or should I do it in php

Thanks

Tomek

Tomek
  • 13
  • 2
  • possible duplicate: http://stackoverflow.com/questions/913841/mysql-conditional-insert – Yasser Souri Jun 13 '11 at 19:53
  • possible duplicate of [How do I update if exists, insert if not (aka upsert or merge) in MySQL?](http://stackoverflow.com/questions/1218905/how-do-i-update-if-exists-insert-if-not-aka-upsert-or-merge-in-mysql) – ypercubeᵀᴹ Jun 13 '11 at 19:57

3 Answers3

4

see here: How do I update if exists, insert if not (AKA "upsert" or "merge") in MySQL?

Community
  • 1
  • 1
Ethan Cabiac
  • 4,943
  • 20
  • 36
2

If you have a UNIQUE index on postID, then you can do something like:

INSERT INTO userpostratings (rating, postID) VALUES ($rating, 8)
    ON DUPLICATE KEY UPDATE rating = $rating;
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • True, it requires a unique index. That's why I wrote "If you have a UNIQUE index...". Can I assume that this was your revenge downvote? – Ted Hopp Jun 13 '11 at 20:23
-1

here you go

http://nl2.php.net/manual/en/function.mysql-affected-rows.php

> mysql_query("UPDATE mytable SET used=1
> WHERE id < 10"); printf ("Updated
> records: %d\n",
> mysql_affected_rows());
Grumpy
  • 2,140
  • 1
  • 25
  • 38