Andy Andy - 4 months ago 24
MySQL Question

How can I retain my variable value within this foreach loop / if statement

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?

$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);

//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.")";


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.