我遇到了最简单的代码问题。出于某种原因,以下代码仅检索数据库的第一行。我正在尝试一个循环,它只是不适合我。这是我的代码:
<?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) {
?>
它只抓取第一行而没有其他行。
答案 0 :(得分:4)
您正在覆盖$result
:
$query = "SELECT * FROM past_due_students....." ;
$result = mysqli_query($dbc, $query) ;
//Loop through the entire table
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
$query = "UPDATE past_due_students SET ...." ;
$result = mysqli_query($dbc, $query) ; <-- OVERWRITTING HERE.
使用其他变量来保存内部查询结果对象。
答案 1 :(得分:1)
通过将下一个查询资源分配给同一个变量,您正在销毁从SELECT查询中获得的$result
资源。
请为UPDATE查询使用其他变量。
所以改变这个:
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$result = mysqli_query($dbc, $query) ;
对此:
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$updateResult = mysqli_query($dbc, $query) ;
答案 2 :(得分:0)
尝试使用其他变量名称
更改$ update的更新结果答案 3 :(得分:0)
你正在覆盖你的循环中的$result
var。您的第二个mysqli_affected_rows
也正在传递数据库对象。
更改
$result = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($dbc) ;
到
$result2 = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($result2) ;