views:

29

answers:

2

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?

A: 

Why do you not just open the connection when needed and close it afterwards.

if(event1){
    $mysli = mysqli_connect();
    // execute your queries
    $mysqli->close();
}else{
Rufinus
+1  A: 

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

damir
Thanks, mysqli_ping worked. I'd like to add, I had to add mysqli.reconnect = On in my php.ini for connection to be automatically reestablished if closed.(Caution: ini_set will not work in this case!!)
Gunjan