Andy Andy - 1 month ago 10
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?
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);
}
?>

Answer

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.

Comments