[英]running a mysqli query inside while loop
I have this php code: 我有这个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);
}
?>
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 由于某种原因,它只会更新数据库中的第一封电子邮件,而当我尝试回显$ row时,只会回显第一封电子邮件
Thanks for the help 谢谢您的帮助
You are rewriting the $result
variable, which is also used in the while loop. 您正在重写
$result
变量,该变量也在while循环中使用。 After the first iteration, $result
is set to the result of the update query, so there are no other rows that can be fetched. 第一次迭代后,将
$result
设置为更新查询的结果,因此没有其他行可以提取。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.