Home > front end >  Duplicate entry condition for MySQL database
Duplicate entry condition for MySQL database

Time:11-11

When I want to write duplicate entry to a UNIQUE column in MySQL I get the error Duplicate entry '' for key 'UNIQUE' . Is it possible to use this error as a condition for if() statement in PHP? I use code below to insert entry in column.

$s = "INSERT INTO `table`(`entry`)
if ($conn->query($s) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $s . "<br>" . $conn->error;
}

CodePudding user response:

The error code for a duplicate key is 1062. The error code is available in $db->errno.

$s = "INSERT INTO `table`(`entry`) VALUES (...)";
if ($conn->query($s) === TRUE) {
    echo "New record created successfully";
} elseif ($conn->errno == 1062) {
    echo "Error: duplicate key";
} else {
  echo "Error: " . $s . "<br>" . $conn->error;
}
  • Related