这是我的代码:
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];
并且跳过CCD_ 10呼叫。