-1

Duplicate entry '20' for key 'user_id'

$userid = its foreign key (20) 


$query = mysql_query("insert into qualification (q_id,course_name,institute_name,pass_year,user_id) values ('','$coursename','$institutename','$passyear','$userid')") or die(mysql_error());

Does anybody have an idea on how to skip this error and add multiple record on the same userid ?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Irfan
  • 58
  • 11
  • 5
    sure, revamp your database structure to remove the unique constraint. – Marc B Jan 05 '15 at 21:25
  • Or consider using REPLACE INTO syntax if you need to overwrite an existing row or inserting a new one if unique key does not already exist. – Mike Brant Jan 05 '15 at 21:27
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). – Jay Blanchard Jan 05 '15 at 21:27
  • hey @MarcB why I remove unique constraint? i used it foregn key – Irfan Jan 05 '15 at 21:28
  • No overwrite add another record same userid – Irfan Jan 05 '15 at 21:28
  • why not i add multiple record same userid ? – Irfan Jan 05 '15 at 21:31
  • Me thinks you should rework your database design based on the operations you want to do. – Tilman Hausherr Jan 05 '15 at 21:35
  • Just look at how your key is defined and the error should be obvious. – developerwjk Jan 05 '15 at 22:18

1 Answers1

1

When you get this error, you have a UNIQUE or PRIMARY key constraint for user_id in your database. As Marc B already said. Remove the unique constraint from the user_id.

You asked Marc:

Why remove unique constraint?

Simply because then you can't have two records with the same user_id in your table. Then you also can't use it as a key for table. You can still use an index on user_id to speed up queries for this field.

Gerd K
  • 1,134
  • 9
  • 23