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 t开发者_如何学Co 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.
You are overwriting the value of $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.
Use a different variable to hold the inner query result object.
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:
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$result = mysqli_query($dbc, $query) ;
To this:
$query = "UPDATE past_due_students SET number_of_declines = $number_of_declines WHERE student_id = $student_id" ;
$updateResult = mysqli_query($dbc, $query) ;
try to change $result of update query with other variable name
You're overwriting the $result
var in your loop it looks like. Also your second mysqli_affected_rows
is being passed the database object.
Change
$result = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($dbc) ;
to
$result2 = mysqli_query($dbc, $query) ;
$number = mysqli_affected_rows($result2) ;
精彩评论