conan conan - 1 year ago 84
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?

$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
/* do something here*/
/* if() every sql2 echo empty result
then do something else

Answer Source

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){
       $echoed = true; //update, so you will know later that something was echoed
   // nothing was echoed