tags:

views:

42

answers:

4

Greetings to all. Newbie here. Question on preventing duplicated entry in my simple web form.

My table record user input from a web form, and distinguished by date e.g. DATE(). How to prevent user with the same name to enter information twice in a single date, e.g. same username cannot be entered twice in the same date, but can be entered at other date?

Hope someone can advice me on this. Thanks is advance.

+2  A: 

Your table should have these:

create table tablename (
...
user_id bigint, -- or whatever
date_created date,
unique key(user_id, date_created)
...
);
ceteras
Thanks for all the advices :)Tried as suggested, it will prevent same entry from same date. But when I change the date to the next date, it will show 'duplicated name' unable to enter record. How to make the same NAME can be entered again on the other DATE?
YS
Perhaps you have an unique key on name alone also?Please run this: `show create table tablename` and post the results.
ceteras
Thanks guys, I manage to get it running. I put in a if..else statement to validate if any of the row with DATE and NAME same, then do not execute enter record, else, enter record. I got this idea from all of you that making NAME and DATE unique. Thank! :)
YS
A: 

Create a unique key on the user and date column

http://dev.mysql.com/doc/refman/5.1/en/create-table.html

onof
+1  A: 

You can simple create a composite primary key. For your case this means that your primary key must consists of a date field as well as the username field.

Javaguru
This is also possible. But the composite PKs are problematic when creating relations with this table. I think UNIQUE index is better approach.
Tomasz Struczyński
I agree! However, I just want to remark that the "NOT NULL" option for unique fields is required (as you did in your table creation code), since a NULL-value for name or date destroys the uniqueness (i.e. it is possible to add the user 'xxx' multiple times if the date is NULL).
Javaguru
A: 

In several ways.

First, you can create index on your table. (i'm using simple table as an example).

CREATE TABLE `test` (
`id` INT NOT NULL ,
`name` VARCHAR( 255 ) NOT NULL ,
`date` DATE NOT NULL ,
PRIMARY KEY ( `id` ) 
) ENGINE = MYISAM;

ALTER TABLE `test` ADD UNIQUE (
`name` ,
`date` 
);

This is MySQL way.

You also should make checks in PHP ,although you can do it when inserting (MySQL will return error and you can check it). But you can make additional SELECT before inserting (SELECT * from test WHERE name=USER AND date=DATE) and check record count. If it's more than 0, you show error.

When saving, you seldom should worry about one additional SQL. If you should, just check MySQL statement for errors (MySQL way :)).

Tomasz Struczyński