使用PHP LOOP更新记录

文森特·奥蒙迪(Vincent Omondi)

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

亚历克斯·霍安斯基

您正在循环生成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注入的信息与其使用字符串连接构建查询,不如使用带有绑定参数的预处理语句请参见此页面此帖子,以获取一些很好的示例。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章