0

I'm trying to run a foreach loop with a IF statement inside. I want to retain the value of $nextupdate so I can insert each $ex into that specific workoutID ($nextupdate). Since the IF statement doesn't run apart from the first time the foreach loop is run, I lose the value of $nextupdate after the first loop. So how can I retain the current value of $nextupdate the first time it is read? Thanks!

$check = 0;
$nextupdate = 0;

foreach($exer->results() as $ex){
    //echo $ex->Name."<br/>";
    //$curId = $ex->ExerciseID;
    //$sql2 = "SELECT * FROM exercises WHERE ExerciseID = ".$curId;
    //$details = DB::getInstance()->query($sql2);

    //print_r($details);
    //echo $details->results()[0]->StartReps;
    //$reps = $details->results()[0]->StartReps;
    //echo $details->results()[0]->StartSets;
    //echo $details->results()[0]->StartWeight;
    //echo "<br>";

    if($check = 0){
       $sql = "SELECT * FROM workoutexercises ORDER BY WorkoutID DESC LIMIT 1";
       $recentworkout = DB::getInstance()->query($sql);
       $updateworkout = $recentworkout->results()[0]->WorkoutID;
       $nextupdate = $updateworkout + 1;
       $check = 1;
       echo $nextupdate;
    }

    $sql = "INSERT INTO workoutexercises (ExerciseID, WorkoutID) VALUES (".$curId.",".$nextupdate.")";
    DB::getInstance()->query($sql);
}
?>
Andy
  • 145
  • 1
  • 11
  • 2
    you should use "$check == 0" in your IF statement, using "$check = 0" will always change the value of "$check" to 0, and will always return true. – Okba Oct 17 '16 at 13:46
  • Oh wow solved my issue! Thanks a lot! – Andy Oct 17 '16 at 13:47

2 Answers2

1

Change your check inside "if" to use double equals like:

if($check == 0){

The value of $nextupdate should retain. There is nothing wrong with that.

Cashif Ilyas
  • 1,619
  • 2
  • 14
  • 22
0

you used single = instead of double == for checking a condition inside the if-statement.if you change it to use ==, your code should work as you want.

$check = 0;
$nextupdate = 0;

foreach($exer->results() as $ex){        
    if($check == 0){
       $sql = "SELECT * FROM workoutexercises ORDER BY WorkoutID DESC LIMIT 1";
       $recentworkout = DB::getInstance()->query($sql);
       $updateworkout = $recentworkout->results()[0]->WorkoutID;
       $nextupdate = $updateworkout + 1;
       $check = 1;
       echo $nextupdate;
    }

    $sql = "INSERT INTO workoutexercises (ExerciseID, WorkoutID) VALUES (".$curId.",".$nextupdate.")";
    DB::getInstance()->query($sql);
}
?>
Jack O'Neill
  • 1,032
  • 2
  • 19
  • 34