I have table named "highscore" like this:
nameQL scoreQL piotr 50And flash game with NAME and SCORE exported to PHP with this names.
How to make this i开发者_如何学Cn PHP file:
- IF (NAME exists in database (nameQL) AND SCORE> this.name.scoreQL){Raplace scoreQL with SCORE WHERE nameQL=NAME}
- IF (NAME doesn't exists){Create new row with NAME and SCORE)
I would use insert .. on duplicate key update ...
statement. Something like this:
insert into highscore set
name = :name,
score = :new_score
on duplicate key update
score = greatest(score, :new_score)
name
column should be indexed as unique
.
Test script:
create table player (
name varchar(32) primary key,
score int not null default 0
);
-- create new players
insert into player set name = 'foo', score = 100
on duplicate key update score = greatest(score, 100);
insert into player set name = 'bar', score = 100
on duplicate key update score = greatest(score, 100);
insert into player set name = 'baz', score = 100
on duplicate key update score = greatest(score, 100);
-- update score of existing player
insert into player set name = 'bar', score = 200
on duplicate key update score = greatest(score, 200);
Output of select * from player
:
+------+-------+
| name | score |
+------+-------+
| bar | 200 |
| baz | 100 |
| foo | 100 |
+------+-------+
精彩评论