gpt4 book ai didi

php - lastInsertId 在第一条记录后没有返回值。我该如何检查呢?

转载 作者:行者123 更新时间:2023-11-29 00:46:38 27 4
gpt4 key购买 nike

我有以下 PHP 脚本,它运行良好,并使用 PDO 事务正确地将所有数据插入 MySQL,但仅在第一次运行时。初次运行后,我尝试再次插入相同的数据。第一个 lastInsertId 然后开始返回 0,因为 email 字段上的 unique key 属性正在停止新的 userId通过 auto_increment 创建值。

在阅读了类似的答案后,我仍然不知道如何检查这种情况并解决问题。我编写了 $userCheck 以便我可以查看来自 $fromParsed 的值是否与数据库中已有的电子邮件地址匹配。我不知道如何获取此查询的值,然后编辑脚本,以便如果用户已经在那里使用相同的电子邮件地址,那么它将获得 $fromParsed 的 userId ,如果 $fromParsed 不存在,则插入它然后继续使用 lastInsertId(); 获取 userId .

我确实尝试过搜索这个问题的答案,但我找不到任何可以为涉及 PDO 交易的类似情况提供明确答案的东西。

抱歉,如果这个问题的答案盲目明显。

try {

$con = new PDO('mysql:host=localhost;dbname=db', 'root', 'password');

$attachmentsQuery = $con->prepare('INSERT INTO attachments SET attachmentName = :attachmentName, content = :content, fileType = :fileType');
$usersQuery = $con->prepare('INSERT INTO users SET email = :email');
$emailsQuery = $con->prepare('INSERT INTO emails SET userId = :userId, subject = :subject, body = :body, attachmentId = :attachmentId');
$userCheck = $con->prepare("SELECT userId FROM users WHERE email = '$fromParsed'");

try {
$con->beginTransaction();

$userCheck->execute();
//Something here?

$usersQuery->bindParam(':email', $fromParsed, PDO::PARAM_STR);
$usersQuery->execute();

$userId = $con->lastInsertId();

$attachmentsQuery->bindParam(':attachmentName', $filename, PDO::PARAM_STR);
$attachmentsQuery->bindParam(':fileType', $fileType, PDO::PARAM_STR);
$attachmentsQuery->bindParam(':content', $content, PDO::PARAM_LOB);
$attachmentsQuery->execute();

$attachmentId = $con->lastInsertId();

$emailsQuery->bindParam(':userId', $userId, PDO::PARAM_INT);
$emailsQuery->bindParam(':attachmentId', $attachmentId, PDO::PARAM_INT);
$emailsQuery->bindParam(':subject', $subject, PDO::PARAM_STR);
$emailsQuery->bindParam(':body', $text, PDO::PARAM_STR);
$emailsQuery->execute();

$con->commit();

} catch(Exception $e) {
$dbo->rollback();
die();
}
} catch(Exception $e) {
error_log($e->getMessage());
}

最佳答案

试一试,

if($userCheck->execute() && $userCheck->rowCount() > 0){
// we have a user.
$data = $userCheck->fetch(PDO::FETCH_ASSOC);
$userId = $data['userId'];
}
else {

$usersQuery->bindParam(':email', $fromParsed, PDO::PARAM_STR);
$usersQuery->execute();

$userId = $con->lastInsertId();
}
//Something here?

简要说明,如果有 rowCount 指定的记录,这会将 $userQuery 的结果放入 $data。如果查询没有返回结果,它将继续执行您的 $userQuery 并为新创建的条目返回一个 userId。

关于php - lastInsertId 在第一条记录后没有返回值。我该如何检查呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10286787/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com