使用PHP LOOP更新记录

时间:2019-05-30 13:57:11

标签: php mysqli

我想使用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列中的所有记录

1 个答案:

答案 0 :(得分:0)

您正在循环生成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 injection的信息。与其通过字符串连接构建查询,不如将prepared statementsbound parameters一起使用。有关一些很好的示例,请参见this pagethis post

相关问题