Reputation: 127
I am trying to change the variable for each day of the week and insert it into a table in sql, but I am having trouble getting the correct value when I cycle trough an array of 7 which represents the seven days of the week. I don't think I am doing this correctly.
$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]
Essentially I am entering 7 records that represents each day f the week but all other information remains the same..anyone know how I can accomplish this? In other words when we look at the db we should see
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 would be a range of times from 1-10 same for iLastTime however i seem to be getting whatever day 1 is, I am sure it is because of the way I am looping through the array.
Upvotes: 2
Views: 61
Reputation: 12208
You run into trouble here:
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]
Instead of checking the $day variable, you passing the individual characters of the var into the if statement, (i.e. $day[0]
= first char, $day[1]
= second, etc.). Instead you want this:
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
Upvotes: 1