phpmysqlidatabase-connectiondaemon

check if mysql connection is valid


I have a long running php script which is basically an infinite loop listening for events (its an xmpp bot), I start the script with nohup php bot.php &.

The raw structure of the script is like

$mysqli = mysqli_connect(...);

while(1) {
  if(event1) {
      // do database action
  } else if(event2) {
      // non database action
      echo "something";
  }
}

When I run the script everything works fine initially. When I come back after a few hours the bot works fine if I issue event2 but fails on issuing event1 with a database related error (PHP Fatal error: Call to a member function bind_param() on a non-object in on line n)

How can I keep the mysql connection valid or is there a way to check if the mysqli connection is valid so that i can reconnect otherwise?


Solution

  • you can ping connection http://php.net/manual/en/function.mysql-ping.php