我正在尝试更改一周中每一天的变量并将其插入sql中的表中,但是当我循环遍历代表一周中七天的7数组时,我很难获得正确的值。 我认为我做的不正确。
$daysOfWeek = [1, 2, 3, 4, 5, 6, 7];
foreach($daysOfWeek as $day){
$sql = "INSERT INTO tblUser (iUserID, iLocID, iDay, iFirstTime, iLastTime)
VALUES (:user, :location, :day, :first, :last)";
$stmt = $dbh->prepare($sql);
$stmt->bindParam (':user', $_SESSION['userID']);
$stmt->bindParam (':location', $_SESSION['locationID']);
$stmt->bindParam(':day', $day);
if($day[0]){
$stmt->bindParam(':first', $decFD->sunEarliest);
$stmt->bindParam(':last', $decFD->sunLatest);
echo $day;
}elseif ($day[1]){
$stmt->bindParam(':first', $decFD->monEarliest);
$stmt->bindParam(':last', $decFD->monLatest);
echo $day;
...continuing until I reach $day[6]
基本上,我要输入7条记录,这些记录代表一周中的每一天,但是所有其他信息都保持不变。.有人知道我该怎么做吗?换句话说,当我们查看数据库时,应该看到
iUser iLocID iDay iFirstTime iLastTime
1 151 1 2 8
1 151 2 3 8
1 151 3 2 8
1 151 4 3 8
1 151 5 2 8
1 151 6 2 8
1 151 7 2 8
iFirstTime的时间范围与iLastTime相同,为1-10 但是我似乎不管第一天是什么,我都相信这是因为我遍历数组的方式。
答案 0 :(得分:1)
您在这里遇到麻烦
if($day[0]){
$stmt->bindParam(':first', $decFD->sunEarliest);
$stmt->bindParam(':last', $decFD->sunLatest);
echo $day;
}elseif ($day[1]){
$stmt->bindParam(':first', $decFD->monEarliest);
$stmt->bindParam(':last', $decFD->monLatest);
echo $day;
...continuing until I reach $day[6]
您无需检查$ day变量,而是将var的各个字符传递到if语句中(即$day[0]
=第一个字符,$day[1]
=第二个字符,等等)。相反,您需要这样做:
if($day === 1){
$stmt->bindParam(':first', $decFD->sunEarliest);
$stmt->bindParam(':last', $decFD->sunLatest);
echo $day;
}elseif ($day === 2){
$stmt->bindParam(':first', $decFD->monEarliest);
$stmt->bindParam(':last', $decFD->monLatest);
echo $day;
...continuing until I reach $day === 7