这是我的代码:
session_start();
/* loops through each row in the global $_SESSION variable which
contains the array and uses the $value to GET the data in the text
boxes and output them */
// studevent_result =
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
echo $studResult;
echo "<br>";
}
// result_postion =
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition = $_GET[$value];
echo $studPosition;
echo "<br>";
}
echo "<br>";
// stud_id =
foreach ($_SESSION['arrayId'] as $value) {
echo $value;
echo "<br>";
}
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE result
SET studevent_result = '00:20:33',
result_position = '6'
WHERE result.stud_id = '12'
";
$updateRow = mysqli_query($conn, $updateQuery);
我使用$_SESSION
变量,它们都存储一个数组。我使用 foreach 循环提取这些数组的结果。
在 $updateQuery
中,我想让 studevent_result
= 上面第一个 foreach 循环的结果,result_position
= 的结果上面的第二个 foreach 循环和 result.stud_id
= 到上面第三个 foreach 循环的结果。我如何修改我的代码才能使其正常工作?
...................................................... ......................................
编辑:
所以在我编辑代码后,我的代码现在看起来像这样:
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult = $_GET[$value];
foreach ($_SESSION['arrayNamePosition'] as $data) {
$studPosition = $_GET[$data];
foreach ($_SESSION['arrayId'] as $idValue) {
echo $idValue;
$updateQuery = "
UPDATE result
SET studevent_result = '$studResult',
result_position = '$studPosition'
WHERE result.stud_id = '$idValue'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
}
}
我嵌套了 foreach 循环。但现在的问题是,对于嵌套循环中的最后一个 foreach 循环,查询中的 $idValue 仅使用数组 $_SESSION['arrayId']
中的最后一个元素。如何修复此问题以循环整个数组,以便查询使用数组中的所有值?
提前致谢。
最佳答案
for( $counter = 0; $counter < count( $_SESSION['arrayNameResult'] ); $counter++ ) {
$studevent_result = current( $_SESSION['arrayNameResult'] );
$result_position = current( $_SESSION['arrayNamePosition'] );
$stud_id = current( $_SESSION['arrayId'] );
next( $_SESSION['arrayNameResult'] );
next( $_SESSION['arrayNamePosition'] );
next( $_SESSION['arrayId'] );
// UPDATE query, this will update the studevent_result and result_position
// column in the database for the specific stud_id.
$updateQuery = "
UPDATE
result
SET
studevent_result = '$studevent_result',
result_position = '$result_position'
WHERE
result.stud_id = '$stud_id'
";
$updateRow = mysqli_query($conn, $updateQuery);
}
请注意,创建准备好的语句并在其上使用 prepare
和 bind_param
会更安全,也是最佳实践。
编辑如果您的$_SESSION
数组使用数字索引,那么您可以简单地执行以下操作:
$studevent_result = $_SESSION['arrayNameResult'][$counter];
$result_position = $_SESSION['arrayNamePosition'][$counter];
$stud_id = $_SESSION['arrayId'][$counter];
并跳过下一个
调用。
关于php - foreach 中的数据用于更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36226947/