Php 获取重复行的记录ID
我有以下疑问:Php 获取重复行的记录ID,php,mysql,pdo,Php,Mysql,Pdo,我有以下疑问: $Query = "INSERT INTO table (name, bio) VALUES ('aname', `abio`)"; $stmt = $conn->prepare($Query); $stmt->execute(); $last_id = $stmt->lastInsertId(); $Query = "INSERT INTO table2 (tid, papers) VALUES ($last_id, '1') ON DUPLICATE KE
$Query = "INSERT INTO table (name, bio) VALUES ('aname', `abio`)";
$stmt = $conn->prepare($Query);
$stmt->execute();
$last_id = $stmt->lastInsertId();
$Query = "INSERT INTO table2 (tid, papers) VALUES ($last_id, '1') ON DUPLICATE KEY UPDATE papers = '2'";
$stmt = $conn->prepare($Query);
$stmt->execute();
表有aname,abio:unique,表2有tid,papers:unique
用户应该插入一个名称和bio,如果它已经存在或不存在,他们将文件插入到表2中,插入名称的id为bio,问题是,如果名称和bio已经存在,我无法获得$last\u id
当PDO告诉我thre是一个重复行时,我如何提取重复行的id?我假设
当PDO告诉我thre是一个重复行时,我如何提取重复行的id
表示表上设置了唯一的字段
我会这样做:
try{
$Query = "INSERT INTO table (name, bio) VALUES ('aname', `abio`)";
$stmt = $conn->prepare($Query);
$stmt->execute();
$last_id = $stmt->lastInsertId();
}catch(PDOExeption $e){
if($e->getCode() != 23000){ //I think it's 23000
//rethrow other PDO errors
throw new PDOException(
$e->getMessage(),
$e->getCode(),
$e
);
}
$Query = "SELECT id FROM table WHERE name = 'aname'";
$stmt = $conn->prepare($Query);
$stmt->execute();
//fetch the first column (id) from the first row, which if its unique there will be only one.
$last_id = $stmt->fetchColumn(0);
}
$Query = "INSERT INTO table2 (tid, papers) VALUES ($last_id, '1') ON DUPLICATE KEY UPDATE papers = '2'";
$stmt = $conn->prepare($Query);
$stmt->execute();
如果尚未将PDO的错误模式转换为异常,则可能必须将其转换为异常
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
但基本上你捕获了PDO抛出的重复异常,然后你得到了唯一的字段,我使用名称,因为你没有说它是什么。然后取失败的值,按该值进行查找。如果您有一个唯一的字段,并且一个值失败,那么您想要的行具有相同的值,这是理所当然的。然后设置$last_id。因此last id由lastInsertId或catch块设置
另外,我没有对此进行任何测试,如果有任何错误,非常抱歉,但理论是正确的。我认为它告诉您有异常?,您可以捕获异常并通过插入失败的唯一字段进行查找。表的键是id,它是主字段,但据我所知,我必须使用另一个查询来检查这个现有的行id,我真的很想知道为什么他们不全面地实现这个功能,而不是为它运行多个查询。你可以执行Insert Ignore,它会忽略错误并继续。因此,这更像是一种责任分离的事情。插入并不真正负责处理重复错误。