View Full Version : Help! "Duplicate entry '1' for key 1"

06-10-2006, 07:35 PM
Hello, I have been working with MySQL and PHP for some days. I'm now trying to do a guestbook, here's my installation creation code:

$link = @mysql_connect($host, $user, $pass) or die("Could not install. Please go back and check your fields. Error: ".mysql_error());
mysql_select_db($db, $link) or die("Could not install. Please go back and check your fields. Error: ".mysql_error());

mysql_query("DROP TABLE IF EXISTS kp_guestbook") or die("Could not delete possible tables. Error: ".mysql_error());

mysql_query("CREATE TABLE kp_guestbook (
id int(8) NOT NULL auto_increment,
name varchar(32),
email varchar(32),
website varchar(32),
date text,
message text,
PRIMARY KEY (id));") or die("Could not insert data into table. Error: ".mysql_error());


and here's my 'sign in guestbook' code:

$link = @mysql_connect($host, $user, $pass) or die("Error: ".mysql_error());
mysql_select_db($db, $link) or die("Error: ".mysql_error());
mysql_query("INSERT INTO kp_guestbook VALUES('1','".$name."','".$email."','".$website."','".$date."','".$message."');") or die("Error: ".mysql_error());
echo ('<a href="guestbook.php">Letīs look at your post!</a>');

Okay, the problem is that I can sign in the guestbook one time, and the second time it gives me this error: "Error: Duplicate entry '1' for key 1"

Can someone help me please?

06-10-2006, 08:19 PM
Your problem is right here:

INSERT INTO kp_guestbook VALUES('1',
you are assigning a value to your ID column. you don't need to assign a value to it sicne it is an auto increment column.

Either name all the columns in your insert or in place of '1' above use NULL. Note that it does not have quote marks around it. If you put quote marks around it then you are assigning the string "NULL" or 'NULL' and not NULL or the absence of value which is what you want.

So do it like this:

insert into yourtable (foo, bar, qux) values ('b','c','d')
leaving the ID column out entirely or

insert into yourtable values (NULL,'b','c','d')
which says to enter NULL into your id field. THe null will be ignored and you will get the next higher id inserted into your column.

For future reference note above that you have '1' since you are assigning a numeric column you would want 1 without the quotes. You should never assign numeric values in quotes. (This is separate issue that the problem you are having, it is just good coding practice).

Kid Charming
06-10-2006, 08:31 PM
Since it's a primary key, id must have a unique value, and you're inserting '1' for every record, which is causing your 'duplicate key' error.

Your column is auto_increment, though, so you shouldn't be manually setting any values for it.

[Edit]Like Guelphdad mentioned long before I finished typing this. :)

06-11-2006, 11:58 AM
Oh yeah, it works! Thank you all, now I understand my typo :thumbsup:

Thanks again!