php - 使用 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 中的所有记录
解决方案
您正在循环中生成 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 注入的信息。不要使用字符串连接构建查询,而是使用带有绑定参数的准备好的语句。有关一些很好的示例,请参阅此页面和此帖子。
推荐阅读
- html - 如何使用 css 将 html 元素与它们的中心距离相等
- python - 我用 bs4 抓取数据我想在找到最后一个值后结束循环
- python - swagger ui中查询参数的基于DRF函数的视图自定义模式装饰器
- python - 防止 KivyMD 多次绘制小部件
- puppet - 在 puppet ensure_packages 包定义中使用命令输出
- snakemake - Snakemake:尝试为多个目录和文件运行规则时出错
- ruby-on-rails - 奇怪的 Rails ActiveRecord 行为
- html - 我的页面上有三列文本,但右列在底部,与其他三列分开
- angular - Angular Ionic - 仅当某个字段是某个值时才验证表单
- c# - 禁用使用 EWS 创建的约会提醒