Sebastian Farham
Sebastian Farham

Reputation: 825

Mysql Duplicate Entry Error On Insert

Something very bizare is happening right now and I don't understand how to fix it... Well, temporarily I do but the solution I found is not how the program should behave...

So I have this employeetimesheets table:

empsheet_id | employee_id |timesheet_status |last_update |isWeekNumber|total_hours|isMonth|isYear|overtimeHours

the variables:

    $isWeekNumber =  $_POST['isWeekNumber'];
    $attendanceyear= $_POST['attendanceyear'];
    $attendancemonth= $_POST['attendancemonth'];
    $employee_id=  $_POST['employee_id'];

the query:

    $insertemptime= $db->prepare("INSERT INTO employeetimesheets (employee_id,isWeekNumber,isMonth,isYear) VALUES (?,?,?,?)");
    $insertemptime->bind_param("iiss",$employee_id,$isWeekNumber,$attendancemonth,$attendanceyear);
    $insertemptime->execute() or die(mysqli_error($db)); 
    $insertemptime->close();

On insert NEW row I receive this error when there is already a row with same employee_id

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Duplicate entry '6748372' for key 'EmployeeTimeSheetsKey''

If I delete the row with the employee_id I'm trying to insert, the query works. I"m confused because it's an insert statement... I should be able to add as many rows I want with the same employee_id, yes? Anybody has an idea what's going on?

Upvotes: 0

Views: 3972

Answers (1)

Nawwar Elnarsh
Nawwar Elnarsh

Reputation: 1069

You've set the field employee_id to unique instead of index

Remove unique index from field and add index again without unique

Example sql code

  1. Check index

    SHOW INDEX FROM employeetimesheets;
    
  2. Remove Index

    ALTER TABLE employeetimesheets DROP INDEX employee_id;
    
  3. Add Index

    CREATE INDEX employeetimesheets ON employee_id;
    

Upvotes: 3

Related Questions