【问题标题】:Data in nested foreach loops used in update query更新查询中使用的嵌套 foreach 循环中的数据
【发布时间】:2016-03-27 12:56:54
【问题描述】:

这是我的代码:

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']中的最后一个元素。如何解决这个问题以循环整个数组,以便查询使用数组中的所有值?

提前致谢。

【问题讨论】:

标签: php mysql arrays foreach nested-loops


【解决方案1】:

如果我理解你的问题,这应该对你有帮助

session_start();
$i = 0;
$studResult = array(); 
foreach ($_SESSION['arrayNameResult'] as $value) {
$studResult[$i] = $_GET[$value]; 
$i++;
}

$studPosition= array();
$i=0;
foreach ($_SESSION['arrayNamePosition'] as $value) {
$studPosition[$i] = $_GET[$value];
$i++;
}


$stud_id = array(); $i=0; 
 foreach ($_SESSION['arrayId'] as $value) {
$stud_id[$i] = $value; $i++;
}

for($j =0; $j<$i; $j++){
  $updateQuery = "
  UPDATE result
  SET studevent_result = '$studResult[$j]',
    result_position = '$studPosition[$j]'
  WHERE result.stud_id = '$stud_id[$j]'
  ";

  $updateRow = mysqli_query($conn, $updateQuery);
}

希望对您有所帮助。快乐编码:)

【讨论】:

  • 谢谢你的回答,我试过了,但由于某种原因,它只使用数组结果中的最后一个元素$stud_id,而不是所有的值。我必须循环查询吗?
  • 那么它的语法会是怎样的呢?
  • 但是我修好了,谢谢老兄这工作得很好:D
猜你喜欢
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 2016-05-01
  • 2013-07-04
  • 1970-01-01
  • 2015-10-09
  • 2017-09-23
  • 1970-01-01
相关资源
最近更新 更多