- 使文件名称列
UNIQUE
- 尝试插入并且如果您有重复密钥错误,请重复添加数字直至成功
随着PDO它可能看起来像:
class QueryException extends RuntimeException { }
class DuplicateKeyException extends QueryException { }
function executeInsert(PDOStatement $stmt) {
try {
$stmt->execute();
} catch (PDOException $e) {
switch ($e->errorInfo[1]) {
case 1062:
throw new DuplicateKeyException($e->getMessage(), null, $e);
default:
throw new QueryException($e->getMessage(), null, $e);
}
}
}
$filename = 'a_page';
$contents = '<title>test</title>';
$stmt = $pdo->prepare('INSERT INTO documents (filename,contents) VALUES (:filename,:contents)');
$repeat = true; $counter = 0;
while ($repeat)
try {
$stmt->bindValue(
':filename',
$filename . ($counter > 0 ? ("-$counter" : '') . '.html'
);
$stmt->bindValue(':contents', $contents);
executeInsert($stmt);
$repeat = false;
} catch (DuplicateKeyException $e) {
$repeat = true;
$counter++;
} catch (QueryException $e) {
$repeat = false;
// error handling here
}
}
在MySQL中还有的对重复KEY语法。你可能想看看 – GordonM 2013-02-17 09:26:08
是的,你可以设置你的字段为UNIQUE – vikingmaster 2013-02-17 09:35:22
http://stackoverflow.com/questions/4702059/insert-contacts-into-database-but-does-not-want-to-duplicate-已经存在的公司 – mithunsatheesh 2013-02-17 09:36:14