同时循环通过mysql数据库列表

时间:2011-08-15 17:12:47

标签: php mysql

好的长话短说,我有一个简单的mailto函数我想为db列表中的每个名称应用/运行。由于它不起作用,我从中删除了所有邮件并进行测试以确保while循环正在与db一起工作,这样做

<?php 


$connect2db = mysqli_connect('127.0.0.1','root','pass','dbnamehere');
if(!$connect2db){
    die("Sorry but theres a connection to database error" . mysqli_error);
}

$sn_query = "SELECT * FROM email_list";

$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);
$sn_rowSelect = mysqli_fetch_array($sn_queryResult);
$to = $sn_rowSelect;

?>

<br/><br/>
////lower part on page //////<br/><br/>


<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
echo "hello there" . " " . $sn_rowSelect['firstname'] . " <br/>";
}
?>

现在这个工作,它通过我的数据库,并从数据库列表打印出我的所有名字。在我的noob大脑中,id认为如果我删除回声线,并输入相应的mailto信息,它将像以前一样循环,但发送邮件到每个名称。所以我这样做了:

<?php 
$sn_query = "SELECT email FROM email_list";

$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);

$sn_rowSelect = mysqli_fetch_array($sn_queryResult);

$to = implode(",",$sn_rowSelect);
$from = $_POST['sender'];
$subject = $_POST['subj'];
$mssg = $_POST['message'];
$headers = "MIME-Version: 1.0rn";
$headers  .= "From: $from\r\n";
$mailstatus = mail($to, $subject, $mssg, $headers);

?>

<br/><br/>
//////////<br/><br/>


<?php
while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {
    $mailstatus;

    if($mailstatus) {
        echo "Success";
    }else{
        echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
    }
}



?>  

现在这会通过电子邮件发送我名单上的第一个名字,但不是其他名字。 我没有得到任何错误,所以不确定问题是什么。我打算用num_rows尝试一个if语句,但在其他地方,在StackOverflow上,有人说这没有帮助,因为while循环自己处理它。 (我尝试过任何一种方式,它仍然只通过电子邮件发送第一个名字)我在这里尝试但无济于事。

1 个答案:

答案 0 :(得分:3)

您尚未在循环中调用mail()函数。你在外面叫它一次。而是尝试以下内容。

假设您已从数据库查询中检索到$to地址(就像您在测试中使用第一个名称所做的那样),请从行集中提取它,并在mail()中使用它:

while($sn_rowSelect = mysqli_fetch_array($sn_queryResult) ) {

    // Get the $to address:
    $to = $sn_rowSelect['email'];

    // Call mail() inside the loop.
    $mailstatus = mail($to, $subject, $mssg, $headers);

    if($mailstatus) {
        echo "Success";
    }else{
        echo "There was a problem sending the mail. Check your code and make sure that the e-mail address $to is valid\n";
    }
}

另请注意,由于您在脚本顶部调用mysql_fetch_array(),因此while循环将从第二行开始。您应该删除在循环之前发生的第一次mysql_fetch_array()调用。

$sn_queryResult = mysqli_query($connect2db, $sn_query) or die("Sorry but theres a connection to database error" . mysqli_error);

// Don't want this...
//$sn_rowSelect = mysqli_fetch_array($sn_queryResult);