1

I have a code that connects to a database. It executes a select statement over a large table using mysql_unbuffered_query. It goes over the records using mysql_fetch_row and finally frees the result. Sometimes, the server where the code is running, disconnects from the network and cannot reach the database. How do I detect this disconnect while reading records with mysql_fetch_row? Here is example code:

$mysql_link  = mysql_connect( 'server', 'uname', 'pword' );

if ( mysql_select_db( 'large_database', $mysql_link ) ) 
{ 
    $query = "SELECT * FROM my_large_table"; 
    $records = mysql_unbuffered_query( $query, $mysql_link ); 
    while ( $record = mysql_fetch_row( $records ) ) // database disconnects here 
    { 
        // do something with the record 
    } 
}
Yani
  • 31
  • 4
  • 2
    mysql_* functions are deprecated as of PHP 5.5.0, and removed as of PHP 7.0.0. Switch your code to use [PDO](https://secure.php.net/manual/en/pdo.prepared-statements.php) or [mysqli](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. – aynber May 30 '17 at 19:34
  • @aynber thank you for your comment. I still need to support mysql_* functions and PHP 5.2+ – Yani May 30 '17 at 19:59
  • Both PDO and mysqli were introduced in PHP 5.0. Unless there's a really really good reason to use mysql, I'd suggest against it. It's buggy, and extremely vulnerable to SQL injection, no matter what you do. That said, you can try using a try/catch block to reconnect if your connection fails. – aynber May 30 '17 at 20:06
  • Yes, I agree with you. Unfortunately, I have to use mysql_. The use case is rather simple - My code will be installed on servers that support only mysql_ and do not have mysqli_ or PDO. – Yani Mar 30 '18 at 12:53
  • Wow, really late response. I'd probably suggest a try/catch block inside a while loop. `$pass = fail; do{ try{ code; $pass = true;} catch(Exception $e){ reconnect code} }while(!$pass);` – aynber Mar 30 '18 at 13:17

0 Answers0