So I have a few for each loops, and I’m trying to echo out the value of $sql at the very end. I’m actually using it with PDO but the echo demonstrates the issue.
$values = "1,2";
$values = explode(',',$values);
$set1 = "2,4";
$set1 = explode(',',$set1);
$set2 = "3,2";
$set2 = explode(',',$set2);
foreach($set1 as $set1val){
if ($set1val==2) {
$sql = "sql one runs";//should run on 1st iteration since 2 will equal 2
echo 'hi';//should echo on 1st iteration since 2 will equal 2
}
}
foreach($set2 as $set2val){
if ($set2val==2) {
$sql = "sql two runs";//should run on 2nd iteration since 2 will equal 2
echo 'bye';//should echo on 2nd iteration since 2 will equal 2
}
}
foreach($values as $value){
echo $sql;
$stmt = $db->query($sql);
}
//The Result Output
'hi' 'bye' 'sql two runs' 'sql two runs' <-- doesn't echo 'sql one runs'
//The Output Required
'hi' 'bye' 'sql one runs' 'sql two runs' <-- Works great, but not outputting this
How can I make it output the output required? Any idea how to do this so the correct statement is echoed/runs?
It never echos
sql one runsbecause the secondforeachoverwrites it withsql two runs. If you need to save the sql strings through the end of the script, you could store them in an array. It’s difficult to specify how as it’s not clear how$valuesis related to the SQL, i.e., which SQL should run with which$value.