开发者

pick a number 1 to 10 on web page

开发者 https://www.devze.com 2022-12-21 21:48 出处:网络
I want to create a web page where a registered user picks a number from 1 to 10. When a user picks a number that number is removed from the available list.

I want to create a web page where a registered user picks a number from 1 to 10. When a user picks a number that number is removed from the available list.

开发者_StackOverflow中文版

Is there a way to guaranty that no 2 or more users can have the same number?

Thanks, rod


I dont know how to do it in the technologies in your tags, but you will need a database, that keeps the state of each number: taken or free. You will have a form on a page, that will submit the number chosen to a form handler that will check the state of the number in the database. If it is taken, you will send the user a page that says "too bad thats taken" or something, if it is free, you will mark it as taken, then send then a page saying they got it.

Your server probably handles requests on a first come first serve basis, and if you use any modern database it will block for you (you just wouldn't want two people trying to get the same number at the same time)

also, the form and the form handler don't have to be different files

and you probably want to record who took what number, so the state of not being taken might was well be the state of not having a username for the number yet.


This question was tagged sql-server so I will offer a SQL Server answer...

If you had a table with a registered user id and the number, with a unique constraint on those two columns, then if inserting the record succeeds that record is claimed by that user, otherwise it is not available.

CREATE TABLE dbo.UserSelection
(
    user_id int not null,
    selection int not null,
    CONSTRAINT UK_UserSelection__user_id__selection UNIQUE (user_id, selection)
)

There are many ways to tell if the insert failed. One way would be to check if there were errors. Execute some SQL similar to this from your app:

SqlCommand cmd = connection.CreateCommand();
cmd.CommandText = "INSERT INTO dbo.UserSelection(user_id, selection) VALUES (@id, @selection); SELECT @@ERROR;";
cmd.Parameters.AddWithValue("@id", userId);
cmd.Parameters.AddWithValue("@selection", selection);
bool youHaveThatSelection = 0 == (int)cmd.ExecuteScalar();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号