0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

勉強メモ: PHPでDBへINSERT実行時にエラー「SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry ... for key 'PRIMARY'」が発生する

Posted at

DBに購入履歴を追加する際、エラーが発生する

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '0-1' for key 'PRIMARY' in C:\xampp\htdocs\skadaip2\program\250904\purchase-output.php:233 Stack trace: #0 C:\xampp\htdocs\skadaip2\program\250904\purchase-output.php(233): PDOStatement->execute() #1 {main}

エラー内容を見ると、登録処理の際にどうやら主キーがかぶってしまっているらしい。

プログラムを確認すると、データ追加時の主キー用のID取得を lastInsertId() で行っていた。

解決

2019年のブログ記事だが、こちらにてlastInsertId()で取得する際には「挿入したテーブルの主キーがAUTO INCREMENT(オートインクリメント)の自動連番である必要」があるとのこと。

DBを確認したところ、なぜが該当のテーブルカラムからAUTO INCREMENTが外れていた。
こちらを修正したところ、問題なく動作するようになりました。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?