Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP CLI continue checking MYSQL database every 2 seconds until user decided to quit

Tags:

php

I don't very much find too much information over the internet about PHP CLI so I am having a hard time figuring out how to finish my code.

Basically, the application should continue checking the MYSQL database every 2 seconds without exiting, unless otherwise the user entered the letter 'q'.

I started it out by just printing the word 'pro' continuously before I implement MYSQL so my code looked like this:

<?php
    fwrite(STDOUT, "This should print word 'pro' continuously\n");
    fwrite(STDOUT, "\tto exit, simply press 'q' and enter\n");

    do {
        fwrite(STDOUT, "pro\n");
    }while (fgetc(STDIN) != 'q');
?>

Pretty much when the user entered 'q', the app terminates, but the problem is it only prints out 'pro' once, and when I pressed enter.

like image 452
weyhei Avatar asked Mar 26 '26 02:03

weyhei


1 Answers

fgetc() will block until there is data to read - in other words, when the script reaches the fgetc() call, the execution will halt until the user inputs something.

In order to work around this, you will need to check whether there is any data to read using stream_select(). You can also use stream_select() to limit the MySQL poll to every 2 seconds. A basic framework would look something like this:

<?php

  // Do all your init work here, connect to DB etc
  $tickerSecs = 2;
  echo "Hello! I've started\n";

  do {

    // Do actual work here
    echo "I'm polling the database\n";

    // See stream_select() docs for an explanation of why this is necessary
    $r = array(STDIN);
    $w = $e = NULL;
    if (stream_select($r, $w, $e, $tickerSecs) > 0) {
      // The user input something
      echo "You input something\n";
      $char = fread(STDIN, 1);
      if ($char == 'q') {
        // The user pressed 'q'
        echo "You told me to quit\n";
        break;
      } else {
        echo "I don't understand '$char'\n";
      }
    }

  } while (TRUE); // Loop forever

  // Do shutdown work here
  echo "I'm shutting down\n";

Note that it is likely that you will have to require your user to press q + enter rather than just q because of the nature of the way these things work - and I don't really understand why this is, maybe someone else can provide the missing piece here?

like image 102
DaveRandom Avatar answered Mar 28 '26 16:03

DaveRandom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!