我目前正在用选定的值更新数据库,但我正在使用for循环来处理每个条目。但我只能对一个选定的数字执行此操作,当前为6,如下所示。
for ($ind = 0; $ind <6; $ind++ )
我该如何让它循环通过所有&然后停下来?
我目前正在使用$_POST&然后将它们提交到此页面上的数据库。如下所示:
for ($ind = 0; $ind <6; $ind++ ) {
$SID = $_POST['SID' . $ind];
$week1 = $_POST ['week1' . $ind];
$week2 = $_POST ['week2' . $ind];
$week3 = $_POST ['week3' . $ind];
$week4 = $_POST ['week4' . $ind];
$week5 = $_POST ['week5' . $ind];
$week6 = $_POST ['week6' . $ind];
$week7 = $_POST ['week7' . $ind];
$week8 = $_POST ['week8' . $ind];
$week9 = $_POST ['week9' . $ind];
$week10 = $_POST ['week10' . $ind];
$sqlQuery = "Update weekbyweek SET Week_1=".$week1.", Week_2=".$week2.", Week_3=".$week3.", Week_4=".$week4.", Week_5=".$week5.", Week_6=".$week6.", Week_7=".$week7.", Week_8=".$week8.", Week_9=".$week9.", Week_10=".$week10." WHERE SID='".$SID."'";
$statement = $db->prepare($sqlQuery);
$statement->execute(['$Week_1' => $week1, '$Week_2' => $week2,'$Week_3' => $week3, '$Week_4' => $week4,'$Week_5' => $week5, '$Week_6' => $week6,'$Week_7' => $week7, '$Week_8' => $week8,'$Week_9' => $week9, '$Week_10' => $week10]);
}
对于使用foreach循环而不是。foreach循环主要用于循环遍历数组的值。
<?php
foreach (array as $value) {
// Code to be executed;
}
您可以设置一个计数来检查数据数组的长度。下面将循环8次,然后停止。
在下面的情况下,数据是一个数组。如果使用databaseso,则必须在数据库中查询所需的X金额设置,将结果存储在变量中,并将计数设置为该变量值。
$data = [0,1,2,3,4,5,6,7];
for ($i=0; $i <= count($data) ; $i++) {
// code...
}
使用此:
$items = [1,2,3,4,5,6,7];
if( !empty( $items ) ){
for ( $i=0; $i < count( $items ) ; $i++ ) {
//code here
}
}
或
foreach( $items as $item ){
//code here
}