我有一个独特的列。正如我所理解的那样,当您尝试将某些数据插入到违反其唯一性的列中时,查询将停止处理。我想要做的只是捕获错误,并继续与其余的行。你如何以最有效的方式使用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