0

I want to have it that if the "tags_name" already exists in the database it will display an error in php rather than a fatel error message.

if(isset($_POST['NewTag']))
{
    $tags_name= $_POST['tags_name'];

    $stmt = $DBcon->prepare("INSERT INTO category (tags_name) VALUES(:tags_name)");

    $stmt->bindparam(':tags_name', $tags_name);
    if ($stmt->execute()) {
        $successMSG = "Succesfull";
    } else {
        $errMSG = "Entry already exists";
    }
}

I'm currently getting this error "Fatal error: Uncaught PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry 'testing' for key 'tags_name' ...." instead my errMSG.

  • **make sure you escape the input coming from user**, this might be useful for you https://stackoverflow.com/a/3146986/9201277 –  Apr 09 '20 at 23:13

1 Answers1

0

Use try catch for error code exist is 1062:

 $tags_name= $_POST['tags_name'];
 $stmt = $DBcon->prepare("INSERT INTO category (tags_name) VALUES(:tags_name)");
 try {
     $stmt->excute(':tags_name', $tags_name);
    } catch (PDOException $e) {
        if ($e->errorInfo[1] == 1062) {
            $messageError = 'Duplicate entry';
        } else {
            throw $e;
        }
  }
Viet Dinh
  • 1,871
  • 1
  • 6
  • 18