1

I want to update data in my database using php loop.

I have tried updating data, but it only updates the last record in my list and returns all the records as null/zero.

// attempting to update data
$rcount_student_lists = mysqli_query($mysqli, $count_student_lists);
while($row2 = mysqli_fetch_row($rcount_student_lists))
    $student_count_count = $row2['0'];

for ($id = 1; $id <=$student_count_count; $id++)
{  
    $sql = "UPDATE exam_data SET score_s = '".${'dd_'.$id}."' WHERE exam_name_s = '".$one."'";
}

if (mysqli_query($mysqli, $sql)) {
    echo juuhead("DETAILS UPDATED SUCCESFULLY");
} else {
    echo "Error updating record: " . mysqli_error($mysqli);
}

I would want it to update all the records in the column score_s

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98

1 Answers1

0

You're generating the SQL string in a loop:

for ($id = 1; $id <=$student_count_count; $id++)
{  
    $sql = ...;
}

But you're only executing it once, because this is outside the loop:

if (mysqli_query($mysqli, $sql)) {

Move the query command inside the loop:

for ($id = 1; $id <=$student_count_count; $id++)
{  
    $sql = ...
    if (mysqli_query($mysqli, $sql)) {
        ...
    } else {
        ...
    }
}

You're also missing braces on your while loop:

while($row2 = mysqli_fetch_row($rcount_student_lists))
$student_count_count = $row2['0'];

Without braces, the while only loops the one line following it. To loop over more than one line, you need to wrap the lines in braces:

while($row2 = mysqli_fetch_row($rcount_student_lists))
{
    $student_count_count = $row2['0'];
    for ($id = 1; $id <=$student_count_count; $id++)
    {
        ...
    }
}

Also, please read about SQL injection. Instead of building queries with string concatenation, use prepared statements with bound parameters. See this page and this post for some good examples.

Alex Howansky
  • 50,515
  • 8
  • 78
  • 98