我有一個獨特的列。正如我所理解的那樣,當您嘗試將某些數據插入到違反其唯一性的列中時,查詢將停止處理。我想要做的只是捕獲錯誤,並繼續與其餘的行。你如何以最有效的方式使用PHP和MySQL來做到這一點?捕獲錯誤並在插入唯一列時繼續
這裏有一個簡單的例子 http://pastie.org/1357001
我真正想知道的是,將循環會出現問題,如果出現錯誤?
我有一個獨特的列。正如我所理解的那樣,當您嘗試將某些數據插入到違反其唯一性的列中時,查詢將停止處理。我想要做的只是捕獲錯誤,並繼續與其餘的行。你如何以最有效的方式使用PHP和MySQL來做到這一點?捕獲錯誤並在插入唯一列時繼續
這裏有一個簡單的例子 http://pastie.org/1357001
我真正想知道的是,將循環會出現問題,如果出現錯誤?
你應該能夠趕上這個錯誤:
try {
// execute SQL query for one record
} catch(Exception $e) {
// handle error here
}
我與這一個ajreal。違反約束不應在PHP中導致異常。你可以從mysqli_stmt::execute測試返回值,或不管它是你正在使用,並處理出現的任何錯誤:
$mysqli = new mysqli('host', 'user', 'password', 'db');
// Prepare an INSERT;
$stmt = $mysqli->prepare('INSERT INTO mytable (id, data) VALUES (?, ?)');
$data = 'Some data';
// Insert 3 rows.
for ($id = 1; $id <= 3 ; $id++) {
// Attempt to insert each row twice.
for ($test = 1; $test <= 2; $test++) {
// Bind the ID and data.
$stmt->bind_param('is', $id, $data);
// Execute the statement.
if ($stmt->execute()) {
// No error.
echo "Inserted row ID $id\n";
} else {
// An error, but no exception.
printf(
"Error %d inserting row ID %d: %s\n",
$stmt->errno,
$id,
$stmt->error
);
}
}
}
打印:
Inserted row ID 1
Error 1062 inserting row ID 1: Duplicate entry '1' for key 'PRIMARY'
Inserted row ID 2
Error 1062 inserting row ID 2: Duplicate entry '2' for key 'PRIMARY'
Inserted row ID 3
Error 1062 inserting row ID 3: Duplicate entry '3' for key 'PRIMARY'
foreach($somethings as $something)
{
try
{
//mysql_query
}
catch(Exception $e)
{
$failed[] = $e;
continue;
}
//process anything else.
}
例外的是要走的路。
嗯......查詢將不會停止**得到處理,除非你指示PHP這樣做,代碼片段? – ajreal 2010-12-07 21:18:18
你目前有什麼代碼? – 2010-12-07 21:24:53
更新了問題 – Breezer 2010-12-07 21:31:13