conan conan - 4 months ago 23
PHP Question

Trying to check if all query inside foreach echo none result, php mysql?

Look at my code, I use foreach to get value from a query result, then use each value to get a query result, if $sql2 echo something, then it will run. But how about if none of of $sql2 echo a result, then I want to do something else outside the foreach loop? how to check if no $sql2 result at all?

<?php
$sql = $wpdb->get_results( $wpdb->prepare("
SELECT whatever FROM table where v=%s ",$test));

foreach($sql as $val){
$dis1 = $val-> whatever;
$sql2 = $wpdb->get_var( $wpdb->prepare("
SELECT wherever from table where val=%s
",$dis1));
if(sql2){
/* do something here*/
}
}
/* if() every sql2 echo empty result
then do something else
*/

Answer

Create a variable early and update it in the loop if something is echoed. At the end, check if it has been updated

$echoed = false;
$sql = $wpdb...

foreach($sql as $val){
   ...
   if($sql2){
       $echoed = true; //update, so you will know later that something was echoed
       ...
   }
}
if(!$echoed){
   // nothing was echoed
}
Comments