I have the following PHP script which runs nicely and inserts all the data into MySQL using the PDO transaction correctly, but only on the first run through. After the initial run through, I try inserting the same data again. The first lastInsertId then starts to return 0 because the unique key attribute on the email field is stopping a new userIdvalue being created via auto_increment.
After reading through similar answers I’m still stuck as to how to check for this situation and fix the problem. I wrote the $userCheck so that I could see if the value from $fromParsed matched that of an email address already in the database. I don’t know how to take the value of this query and then edit the script so that if a user is already in there with the same email address then it gets the userId of $fromParsed, and if $fromParsed isn’t already in there, insert it then continue using lastInsertId(); to get the userId.
I did try searching for an answer to this but I couldn’t find anything that gave me a clear answer for a similar situation involving PDO transactions.
Sorry if the answer to this is blindly obvious.
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());
}
Give this a try,
Brief explanation, this will place the results from the $userQuery into $data if there is a record dictated by the rowCount. If the query returns no results, it will continue to execute your $userQuery and return a userId for the newly created entry.