首页 > 解决方案 > 使用 PHP 循环更新记录

问题描述

我想使用 php 循环更新我的数据库中的数据。

我尝试更新数据,但它只更新列表中的最后一条记录并将所有记录返回为空/零。

// 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);
}

我希望它更新列 score_s 中的所有记录

标签: phpmysqli

解决方案


您正在循环中生成 SQL 字符串:

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

但是你只执行一次,因为这是在循环之外:

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

在循环内移动查询命令:

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

您的 while 循环中还缺少大括号:

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

如果没有大括号,while 只会循环它后面的一行。要遍历多行,您需要将这些行括在大括号中:

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

另外,请阅读有关SQL 注入的信息。不要使用字符串连接构建查询,而是使用带有绑定参数的准备好的语句。有关一些很好的示例,请参阅此页面此帖子


推荐阅读