简体   繁体   中英

Using a condition in a while loop

I have this code

$dbh = new PDO('mysql:host=localhost;dbname=odesk', 'root', '123456');
$sth = $dbh->prepare("SELECT id,msisdn from new_r4 limit 1,10");
$sth2 = $dbh->prepare("SELECT status from flag where id = 1");
$sth->execute();
$sth2->execute();

while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {
    $result2 = $sth2->fetch(PDO::FETCH_ASSOC);

    $flag = $result2['status'];
    $the_number = $result['msisdn'];
    $id = $result['id'];

    while ($flag == 0) {
        echo 'Waiting.......' . PHP_EOL;
        sleep(1);
    }
    //Part of the condition,just added
    while ($flag == 1) {
        echo $the_number . '   ' . $id .'  ' . PHP_EOL;
        sleep(1);
    }
}

which is aa cli script that displays some numbers from my address book if a certain condition is met.If a the flag is 0 then no number shall be displayed and when the flag is 1 ,then display the number.

The problem is,i can't find the right condition to use after

while ($flag == 0) {
    echo 'Waiting.......' . PHP_EOL;
    sleep(1);
}

The if , else and case do not wait up until the flag is 1.

What condition can i use to get the script to display the numbers when $flag == 1 ?.

The while ($flag == 0) { is infinite and will never break out ($flag never changes within the loop); so the rest of the code is never executed.

Why not just use a simple if/else statement ?

if($flag===1){
    echo $the_number . '   ' . $id .'  ' . PHP_EOL;
}else{
    echo 'Waiting.......' . PHP_EOL;
}

You're using $result2 and $result1 . Your $flag will always be the value id = 1 because the WHERE clause never changes - so either $flag will always be either 1 or another value (from your question, it's going to always be another value). Either change your query to join the table, or query whilst in the while loop.

Assuming new_r4.id = flag.id

SELECT r.`id`, r.`msisdn`, f.`status`
FROM new_r4 r
LEFT JOIN flag f
ON r.id = f.id
LIMIT 1, 10

Change your code to become

while ($result = $sth->fetch(PDO::FETCH_ASSOC)) {

    $flag = $result['status'];
    $the_number = $result['msisdn'];
    $id = $result['id'];

Now all you need to do is check $flag is equal to 1 , and you're golden.

if($flag == 1) {
   echo $this_number . PHP_EOL;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM