如何在php和mysql中使用数组和for循环更新表列?
Posted
技术标签:
【中文标题】如何在php和mysql中使用数组和for循环更新表列?【英文标题】:How to update table column using array and for loop in php and mysql? 【发布时间】:2016-01-04 06:06:32 【问题描述】:for ($key=0; $key < count($_POST['marks']); $key++)
$from_marks = $_POST['from'][$key];
$get_marks = $_POST['marks'][$key];
//echo $from_marks." ";
if($get_marks > $from_marks)
// header("location: ../../pages/marks.php?over=err");
// break;
echo "Cant add more marks <br/>";
else
echo $get_marks."<br/>";
$update_marks_query = $db->prepare(
"UPDATE sc_marks SET get_marks='"
.$get_marks
."' WHERE _sid='$sc_foreign_id' AND exam_type='$select_exam_type' ");
$update_marks_query -> execute();
执行代码时出现问题,我在表的每一行中获取了最后一个获取的值。
更新后的数据结果:
【问题讨论】:
所有行最终都包含相同数据这一事实表明UPDATE
语句的WHERE
子句始终匹配表中的每一行。如果不知道使用的变量$sc_foreign_id
和$select_exam_type
是在哪里以及如何定义的,以及它们的相关字段在数据库中包含什么样的数据,我真的无法给出更准确的答案。
顺便说一句,您应该在for
循环$query = $db->prepare("UPDATE sc_marks SET get_marks=? WHERE _sid=? AND exam_type=?");
之前准备更新语句,然后在每次迭代期间使用$query->execute($get_marks, $sc_foreign_id, $select_exam_type);
附加参数。您当前的方法存在安全风险,除了效率低下。阅读SQL injection。
【参考方案1】:
我建议您在 for 循环之前准备更新语句
$query = $db->prepare("UPDATE sc_marks SET get_marks=? WHERE _sid=? AND exam_type=?");
for ($key=0; $key < count($_POST['marks']); $key++)
$from_marks = $_POST['from'][$key]; //add some validation here
$get_marks = $_POST['marks'][$key]; //e.G with regex
//echo $from_marks." ";
if($get_marks > $from_marks)
// header("location: ../../pages/marks.php?over=err");
// break;
echo "Cant add more marks <br/>";
else
echo $get_marks."<br/>";
$query->execute($get_marks, $sc_foreign_id, $select_exam_type);
//Then attach the parameters during each iteration within the loop
您当前的方法存在安全风险,除了效率低下。了解 SQL 注入。
【讨论】:
【参考方案2】: <?php
include "./connection/config.php";
if(isset($_POST['btn_update_marks']))
$sc_foreign_id = $_POST['sc_foreign_id'];
$select_exam_type = $_POST['select_exam_type'];
for($key=0; $key<count($_POST['marks']); $key++)
$from_marks = $_POST['from'][$key];
$get_marks = $_POST['marks'][$key];
echo $from_marks." ";
if($get_marks > $from_marks)
// header("location: ../../pages/marks.php?over=err");
// break;
echo "Marks Vadhu Chhe <br/>";
else
echo $get_marks."<br/>";
$update_marks_query = $db->query("UPDATE sc_marks SET get_marks='".$get_marks."' WHERE _sid='$sc_foreign_id' AND exam_type='$select_exam_type' ");
// else
// $update_marks_query = $db->prepare("UPDATE sc_marks SET get_marks='$get_marks' WHERE _sid='$sc_foreign_id' ");
// $update_done = $update_marks_query -> execute();
//
// if($update_done)
// echo "Successfully Updated";
// header("location: ../../pages/marks.php?add-marks=yes");
//
// else
// echo "Error";
// header("location: ../../pages/marks.php?add-marks=error");
//
?>
【讨论】:
以上是关于如何在php和mysql中使用数组和for循环更新表列?的主要内容,如果未能解决你的问题,请参考以下文章