1

I am using PHP to make an ODBC to a MS SQL Server 2012 database. My query results were not coming in because there is an automatic timeout for the odbc_exec command. I have changed my code (and it now is working) to

$myQuery = odbc_prepare($myConnection, $mySQLQuery);
odbc_setoption($myQuery, 2, 0, 6000); // 100 minute timeout
odbc_execute($myQuery);

as per the suggestion of this answer. I am wondering how I can tell if this query does time out, so that I can report it as an error or something of that sort.

Community
  • 1
  • 1

1 Answers1

0

Upon further investigation, I have come up with the following solution, please let me know if you have a better one!

Running my program in the command prompt with the argument -d display_errors gave the warning:

SQL error: [Microsoft][ODBC Driver 13 for SQL Server]Query timeout expired, SQL state S1T00 in SQLExecute in myPHPfile.php on line 31

From here, I used the basic idea from this answer as well as this technique to create my own error handler and do something special when the query timed out as follows

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
    if (strpos($errstr, "Query timeout expired") !== false && $errno = E_WARNING){ 
        # If there is a warning with text containing "Query timeout expired"
        # Do your handling here
    }

    # Execute PHP internal error handler as well
    return false;
}

set_error_handler("myErrorHandler");

I searched the string for "Query timeout expired" because most likely there are other $errstr messages, depending on the ODBC; you may have to fiddle with this to make it work for you. I returned false in my custom error handler so the default handler would also run.

Community
  • 1
  • 1