1
   <input type="text" name="CODE" size="25" placeholder="Insert code..." />

   <input type="text" name="NAME" size="25" placeholder="Insert name..." />

  if(isset($_POST['CODE'], $_POST['NAME'])){

         $querystring='INSERT INTO Company (Name, Code) VALUES(:Name,:Code);';

         $stmt = $pdo->prepare($querystring);
         $stmt->bindParam(':Name', $_POST['NAME']);
         $stmt->bindParam(':Code', $_POST['Code']);
         $stmt->execute();

}

Hey!

The problem I'm having is displaying SQL Errors in a nicer way in PHP. Let's say I insert a Company with Code '123' and Name 'ABC'. And then after insert a Company with Code '123' I will obviously get an error that there is a duplicate entry of that Code.

The error that I'm getting is

Warning: PDOStatement::execute(): SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry

I wan't to simply be able to replace this error or warning with a message telling the user that the code he's trying to insert already exists.

Hope I manage to explain, Thanks!

1 Answer 1

1

try to handle tour query like this hope it will work for you

try{
    $pdo->query("INSERT INTO `table`(`name`,`value`)`VALUES('name','value')");
}
catch (PDOException $e) {
    if($e->errorInfo[0] == '23000' && $e->errorInfo[1] == '1062'){
        throw new CustomException("Bla bla already exists");
    } 
    else {
    throw $e;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.