1

This my code syntax all conditions are working but last else is not working. I found solution in there https://stackoverflow.com/a/5930255/7688968 and I am used break 2 but still not working. How can I solve that?

<?php
$rows = $wpdb->get_results( "SELECT * FROM test WHERE approve_status = '1'" );

if($rowcount>0)
{
    foreach ($rows as $row)
    { 
        if ( is_user_logged_in() ) 
        {
            echo 'I am user';
            $demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");

            foreach($demo as $demos)
            {

                if(!empty($demos->id)){
                    echo 'I am IF';
                     break 2;
                }

                else{
                    echo  'I am last ELSE';
                }
            }
        }
        else{
            echo 'I am guest user';
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Sakib
  • 126
  • 20

3 Answers3

1

You are doing the else in the wrong place, it should be done instead of the foreach...

   $demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");

    if(!empty($demo)){
        foreach($demo as $demos)
        {
            echo 'I am IF';
        }
    }
    else{
        echo  'I am last ELSE';
    }

So the logic is that if no records are returned then display your message.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
0

Because the break doesn't break if's. You need to break the foreachs only once, so it's just break;

That else actually doesn't run, because the if is not false. If it uses break in the ifs, else won't run at all. The innermost else runs only, if the very first id of $demos is empty. The second only when if the user is not logged in. These don't relate too much for the foreach cycles.

kry
  • 362
  • 3
  • 13
  • I think its fine. He is probably debugging his code and is trying to break the outer loop, that is why there s a `break 2` there. Probably `is_user_logged_in()` doesnt return false, that is why the if condition is always true – Nodir Rashidov Jul 10 '17 at 07:09
0

Move whole foreach block in the function and return from it when needed. For example:

if($rowcount>0)
{
    doStuff($rows);
}

function doStuff($rows) {
    global $wpdb, $curentmail;

    foreach ($rows as $row)
    { 
        if ( is_user_logged_in() ) 
        {
            echo 'I am user';
            $demo = $wpdb->get_results("SELECT * FROM abc WHERE user_mail = '$curentmail'");

            foreach($demo as $demos)
            {

                if(!empty($demos->id)){
                    echo 'I am IF';
                    return;
                }

                else{
                    echo  'I am last ELSE';
                }
            }
        }
        else{
            echo 'I am guest user';
        }
    }
}