を取り扱い、私は次のようないくつかのデータファイルを持っている:PHP PDO TRY。重複
- table 1 - table 2 - table 3
id val id val id val
============ ========== ===========
1 one 1 uno 1 un
2 two 4 dos 6 deux
3 three 5 tres 7 trois
私は期待してデータベースに挿入しようとしている:
= result table
id val
============
1 one
2 two
3 three
d1 uno
4 dos
5 tres
dd1 un
6 deux
7 trois
データベースの構造は次のとおりです。
= sqlite database file: data.db
CREATE TABLE register (
id VARCHAR(3) PRIMARY KEY,
val VARCHAR(16)
);
私はこの種の解決策を思いついた:
<?php
$table1 = array("1"=>"one","2"=>"two","3"=>"three");
$table2 = array("1"=>"uno","4"=>"dos","5"=>"tres");
$table3 = array("1"=>"un","6"=>"deux","7"=>"trois");
$fileHandle = new PDO("sqlite:data.db");
$fileHandle->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
foreach($table1 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3
foreach($table2 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."','".$value."');");
}catch(PDOException $e){
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// keys: 1, 2, 3, d1, 4, 5
foreach($table3 as $key => $value){
try{
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('".$key."', '".$value."');");
}catch(PDOException $e){
echo " getCode : ".$e->getMessage()."\n";
if($e->getCode()=='23000'){ // if key exists, add a "d" to differentiate
$fileHandle->exec("INSERT INTO `register` (id,val) VALUES ('d".$key."', '".$value."');");
}
}
}
// Signals error on the INSERT in the CATCH body
?>
しかし、鍵の2番目の出現に立ち往生しています。この例では、重複キー(d1)を生成しています。
SQLSTATE[23000]: Integrity constraint violation: 19 UNIQUE constraint failed: register.id
私は繰り返しパターンを見ることができますが、凝縮する方法はわかりません。または、修正されたキーの再試行。
ご入力いただきありがとうございます。
私の質問に集中しようとしています。いずれの構造も変更することはできません。データとデータベースはすでに存在しています(何千ものレコードがあります)。目標は重複するIDを挿入することです(制約が防止する)。したがって、引き数のために、同じid1,1,1の3つのレコードを1、d1、dd1としてデータベースに挿入します。 –