简体   繁体   中英

running a mysqli query inside while loop

I have this php code:

<?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);    
}

?>

It works just fine; however, when I add a query to it only the first email in my database is sent here it what it looks like.

<?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);
}

?>

for some reason it only updating the first email in the database and when I try to echo out $row only the first email is echoe'd

Thanks for the help

You are rewriting the $result variable, which is also used in the while loop. After the first iteration, $result is set to the result of the update query, so there are no other rows that can be fetched.

You can write this, for example:

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

That should work (if there is no other mistake).

不确定mysqli_real_escape_string作为函数存在...或者至少php.net对此不了解..此外,对于mysql_real_escape_string (我想您要使用的参数),参数会mysqli_real_escape_string

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM