在循环中运行mysqli查询

时间:2013-12-10 18:15:25

标签: php

我有这个PHP代码:

<?php 
//include database
include 'db.php';
//grab the emails from the database
$sql = "SELECT email FROM `emails`";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
    // update the database
    //sanitinzw
    $row = mysqli_real_escape_string($con, $row['email']);
    //mail the emails 
    $to      = $row;
    $subject = 'HELLOO';
    $message = 'alooooo';
    $headers = 'From: admin@admin.com' . "\r\n" .
               'Reply-To: admin@admin.com' . "\r\n" .
               'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);    
}

?>

它运作得很好;但是,当我向它添加一个查询时,我的数据库中的第一封电子邮件就会被发送到它的外观。

<?php 
//include database
include 'db.php';
//grab the emails from the database
$sql = "SELECT email FROM `emails`";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)){
    // update the database
    //sanitinzw
    $row = mysqli_real_escape_string($con, $row['email']);
    //mail the emails 
    $to      = $row;
    $subject = 'hello';
    $message = 'aloooooo';
    $headers = 'From: admin@admin.com' . "\r\n" .
               'Reply-To: admin@admin.com' . "\r\n" .
               'X-Mailer: PHP/' . phpversion();

    mail($to, $subject, $message, $headers);    

    $sql = "UPDATE `emails` SET times_used = times_used + 1 WHERE email = '$row' ";
    $result = mysqli_query($con, $sql);
}

?>

由于某种原因它只更新数据库中的第一封电子邮件,当我尝试回显$ row时,只有第一封电子邮件回复

感谢您的帮助

2 个答案:

答案 0 :(得分:3)

您正在重写$result变量,该变量也在while循环中使用。在第一次迭代之后,$result被设置为更新查询的结果,因此没有其他行可以被提取。

你可以这样写,例如:

$sql = "UPDATE `emails` SET times_used = times_used + 1 WHERE email = '$row' ";
$result2 = mysqli_query($con, $sql);

这应该有用(如果没有其他错误)。

答案 1 :(得分:0)

不确定mysqli_real_escape_string作为一个函数存在...或者至少php.net不知道它...更多,mysql_real_escape_string(我猜你想要使用的)反过来说:

$row = mysql_real_escape_string($row['email'],$con);