Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP MYSQL PDO -> Fatal Error 23000 eventhough a special procedure is in place

Tags:

php

mysql

pdo

I have a table in my db. My table has several fields including an auto-incremented id field set as primary key, and one other field called 'reference' that I did set as unique. To populate that table, I have a php script that insert records in that table using pdo. Every time an insert has been made successfully (meaning the 'reference' did not exist in the table), I increment a variable called $newOnes. If the value 'reference' is already in the table, an exception with the code 23000 is triggered. In that case, I increment another variable called $doublons. Unfortunately my script is triggering a fatal error with exception 23000 when the while loop is "handling" the last record of the table. And I do not get it. Thank you in advance for your help. Cheers. Marc.

My php code:

try {
  $connexion = connexion('localhost', 'user', 'user', 'mydb');
  $connexion->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $qry_bat = $connexion->query('SELECT...');
  $ins_db = $connexion->prepare('INSERT...');
}
catch (PDOException $e) {
  echo $e->getMessage();
}

while($row = $qry_bat->fetch(PDO::FETCH_ASSOC)) {
  try {
    $ins_db->execute(array(...));
    $newOnes++;
  }
  catch (PDOException $e) {
    if ($e->getCode() != 23000) {
      echo '<span class="msg-alert">'.$e->getMessage().'</span>';
    } else {
      $doublons++;
    }
  }
}

The fatal error I am getting (note that line 22 refers to the while(...) line):

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]:  
Integrity constraint violation: 1062 Duplicate entry 'theFieldContentOfTheLastRecordOfTheTable' for key 'theFieldNameReference' in  
/myFilePath/file.php:22 Stack trace: #0 /myFilePath/file.php(22): PDOStatement->fetch(2)  
#1 {main} thrown in /myFilePath/file.php on line 22

EDIT //////////

original table (things to mentionne):
auto incremented id

table to insert in (things to mentionne):
auto incremented on id field
UNIQUE INDEX on reference

like image 226
Marc Avatar asked Oct 23 '25 16:10

Marc


1 Answers

(Upgrading to an answer)

Looks like this bug, which is still open after almost five years; try instead:

while (true) {
  try {
    $row = $qry_bat->fetch(PDO::FETCH_ASSOC);
    if (!$row) break;
    $ins_db->execute(array(...));
    $newOnes++;
  }
  catch (PDOException $e) {
    if ($e->getCode() != 23000) {
      echo '<span class="msg-alert">'.$e->getMessage().'</span>';
    } else {
      $doublons++;
    }
  }
}
like image 183
eggyal Avatar answered Oct 26 '25 07:10

eggyal