PHP电子邮件如果SQL条目是新的,如果更新没有电子邮件

时间:2015-09-04 19:25:10

标签: php mysql on-duplicate-key

当有新用户添加到数据库时,我收到一封电子邮件(通过PHPMailer)。如果电子邮件(密钥)已存在且ON DUPLICATE KEY UPDATE功能,则更新DB。但是,我不希望电子邮件在更新时发送,只有在新邮件发布时才会发送。如何检查(使用PHP)SQL结果是更新还是插入,然后使用IF语句发送/不发送电子邮件?

$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';
}

编辑1: 我可能会说这个错了,但是$ result返回1,这似乎是正确的,但是 - &gt; affected_rows是空的。

$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 个答案:

答案 0 :(得分:1)

根据文档:https://dev.mysql.com/doc/refman/5.1/en/mysql-affected-rows.html

  

对于INSERT ... ON DUPLICATE KEY UPDATE语句,如果将行作为新行插入,则affected-rows值为1,如果更新现有行,则为2。

因此,请使用:mysql_affected_rows,或者您所选择的非弃用/非过时数据库中的等效项。