在mysql字段中发送值为1的电子邮件用户

时间:2014-08-20 02:29:59

标签: php mysql

我有一个每晚午夜执行的php文件。如果警报字段中的值为“1”,它会查询表中所有用户的mysql并返回其电子邮件地址。我试图让这个文件只发送给那些用户。目前我通过电子邮件发送数据库$to = $row['email'];中的每个电子邮件地址来工作,但我不能让它只向已注册警报的选定用户发送电子邮件。

<?

$con=mysqli_connect("localhost","root","","DB1");
// Check connection
if (mysqli_connect_errno()) {
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM users");



##email users their account balances


$sql = mysqli_query("SELECT * FROM users WHERE alerts = '1'");
$recipients = array();
while($row = mysqli_fetch_array($result)){ 

    $recipient[]=$row['email'];

    $to = $row['email'];
    $subject = "Your account has received a deposit.";
    $body = "Hello,\n\nWe have added 1 DOGE and .0000001 BTC to your account. Go to www.bitcoinchew.com/Profile to withdrawl. $
    if (mail($to, $subject, $body)) {
        echo("<p>Email successfully sent!</p>");
    } else {
        echo("<p>Email delivery failed…</p>");
    }
  }
?>

2 个答案:

答案 0 :(得分:0)

你的while循环应该是

while($row = mysqli_fetch_array($sql)){ ...

答案 1 :(得分:0)

好的,这里。首先,您为查询调用了错误的变量$result并使用了mysqli_query()两次。

$result = mysqli_query($con,"SELECT * FROM users");

while($row = mysqli_fetch_array($result))

摆脱$result = mysqli_query($con,"SELECT * FROM users");

并使用$sql = mysqli_query($con,"SELECT * FROM users WHERE alerts = '1'");

然后使用while($row = mysqli_fetch_array($sql)){

您的mail() headers中也遗漏了From:,这很可能最终会被垃圾邮件收集或被“标记”为垃圾邮件。 From将显示为您的服务器,而不是电子邮件地址。

$from = "you@example.com";

然后在$headers,

中添加if (mail($to, $subject, $body))
if (mail($to, $subject, $body, $headers))

to withdrawl. $末尾也有一个缺少的引号和分号,这会导致解析错误。

to withdrawl. $";


这是一个有效的改写:

<?php

$con = mysqli_connect("localhost","root","","DB1");

    if (mysqli_connect_errno()) {
     echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

$sql = mysqli_query($con,"SELECT * FROM users WHERE alerts = '1'");

$recipients = array();

while($row = mysqli_fetch_array($sql)){ 

    $recipient[]=$row['email'];

    $from = "you@example.com"; // <= change it to your own

    $to = $row['email'];
    $subject = "Your account has received a deposit.";

    $body = "Hello,\n\nWe have added 1 DOGE and .0000001 BTC to your account. Go to www.bitcoinchew.com/Profile to withdrawl. $";

    $headers = "From: $from";


    if (mail($to, $subject, $body, $headers)) {
        echo("<p>Email successfully sent!</p>");
    } else {
        echo("<p>Email delivery failed…</p>");
    }
}

<强>脚注:

$recipients = array();不是必需的。您只需删除括号$recipient=$row['email'];

即可

这两种方法无论哪种方式都可以工作,只需要更多的按键操作。


<强>个性化

如果您有一行人名,您可以使用以下方式对其进行个性化设置:

$name=$row['name'];将其添加到$recipient=$row['email'];

之上

然后执行$body = "Hello $name,\n\nWe have added...