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

*爱你&永不变心* 提交于 2019-12-02 09:36:22

问题


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:


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.



来源:https://stackoverflow.com/questions/32405223/php-email-if-sql-entry-is-new-no-email-if-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!