PHP Email if SQL entry is new, no email if update

2020-04-21 04:48发布

I have an email that gets sent out (via PHPMailer) when a new user is added to a database. The DB is updated if the email (key) already exists with the ON DUPLICATE KEY UPDATE function. However, I don't want the email to send if it is updated, only when it's new. How can I check (with PHP) if the SQL result was an update or an insert, and then use an IF statement to send/not send the email?

$sql = "INSERT INTO premium_waitinglist (date, email, ip) VALUES ('".$serverDate."', '".$_POST['user-email']."', '".$userIP."') ON DUPLICATE KEY UPDATE waiting = 1";
if ($conn->query($sql) == true) {} else { echo "<kbd>Error: ".$conn->error."</kbd>";}
$mail = new PHPMailer;

$fromEmail = $_POST['user-email'];

$body = file_get_contents($urlBody);

$mail->isSMTP();
$mail->Host = $mailHost;
$mail->SMTPAuth = true;
$mail->Username = $mailUsername;
$mail->Password = $mailPassword;
$mail->Port = 2525;

$mail->From = $fromEmail;
$mail->FromName = $fromName;
$mail->addAddress($toEmail, $toName);

$mail->Subject = $mailSubject;

$mail->isHTML(true);

$mail->Body = $body;

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

EDIT 1: I may be calling this wrong, but $result is returning 1, which seems right, but the ->affected_rows is empty.

$sql = "INSERT INTO premium_waitinglist (date, email, ip) VALUES ('".$serverDate."', '".$_POST['user-email']."', '".$userIP."') ON DUPLICATE KEY UPDATE waiting = 1";
$result = $conn->query($sql);
if ($result == true) {} else { echo "<kbd>Error: ".$conn->error."</kbd>";}
echo $result;
echo $result->affected_rows;

if ($result->affected_rows == 1) {

1条回答
小情绪 Triste *
2楼-- · 2020-04-21 05:26

As per the docs: https://dev.mysql.com/doc/refman/5.1/en/mysql-affected-rows.html

For INSERT ... ON DUPLICATE KEY UPDATE statements, the affected-rows value is 1 if the row is inserted as a new row and 2 if an existing row is updated.

So, use: mysql_affected_rows, or whatever equivalent is on your non-deprecated/non-obsolete DB library of choice.

查看更多
登录 后发表回答