如何在 PHP 中使用 While 循环?
我在最简单的代码上遇到了麻烦。由于某种原因,以下代码仅检索数据库中的第一行。我正在尝试 while 循环,但它对我不起作用。这是我的代码:
<?php
//Connect to the database
require_once('mysql_connect.php') ;
$query = "SELECT * FROM past_due_students WHERE charged_today = 'No' ORDER BY past_due_id" ;
$result = mysqli_query($dbc, $query) ;
$number_of_students = mysqli_num_rows($result)
if ($number_of_students >= 1) {
//Loop through the entire table
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$student_id = $row['student_id'] ;
$number_of_declines = $row['number_of_declines'] - 1;
//Update the number of declines
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$result = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($dbc) ;
if ($number == 1) {
echo '<p><b>The number of declines has been successfully updated.</b></p>' ;
} else {
echo $query ;
}
}//END while loop
}//END if ($number_of_students >= 1) {
?>
它只抓取第一行,而不抓取其他行。
I am having trouble with the most simple piece of code. For some reason, the following code only retrieves the first row out of the database. I am trying a while loop and it just is not working for me. Here is my code:
<?php
//Connect to the database
require_once('mysql_connect.php') ;
$query = "SELECT * FROM past_due_students WHERE charged_today = 'No' ORDER BY past_due_id" ;
$result = mysqli_query($dbc, $query) ;
$number_of_students = mysqli_num_rows($result)
if ($number_of_students >= 1) {
//Loop through the entire table
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$student_id = $row['student_id'] ;
$number_of_declines = $row['number_of_declines'] - 1;
//Update the number of declines
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$result = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($dbc) ;
if ($number == 1) {
echo '<p><b>The number of declines has been successfully updated.</b></p>' ;
} else {
echo $query ;
}
}//END while loop
}//END if ($number_of_students >= 1) {
?>
It is only grabbing the first row and none of the other rows.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在覆盖
$result
的值:使用不同的变量来保存内部查询结果对象。
You are overwriting the value of
$result
:Use a different variable to hold the inner query result object.
通过将下一个查询资源分配给同一变量,您将破坏从 SELECT 查询获得的
$result
资源。请为 UPDATE 查询使用不同的变量。
因此,将其更改
为:
You are destroying the
$result
resource you got from the SELECT query by assigning the next query resource to the same variable.Please use a different variable for the UPDATE query.
So change this:
To this:
尝试使用其他变量名称更改更新查询的 $result
try to change $result of update query with other variable name
您正在覆盖循环中的
$result
var,它看起来像。此外,您的第二个mysqli_affected_rows
正在传递数据库对象。更改
为
You're overwriting the
$result
var in your loop it looks like. Also your secondmysqli_affected_rows
is being passed the database object.Change
to