Erik Åstrand
Erik Åstrand

Reputation: 379

SQL - Handing errors in PHP (Duplicate Entry)

   <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!

Upvotes: 1

Views: 1484

Answers (1)

Faizan Khan
Faizan Khan

Reputation: 628

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;
    }
}

Upvotes: 1

Related Questions