I am a newbie to both PHP and WordPress (but do ok in C#), and am struggling to understand the error handling in a custom plugin I am attempting to write. The basics of the plugin is to query an exsiting MSSQL database (note its not the standard MYSQL db…) and return the rows back to the screen. This was working well, but the hosting provider has taken my database offline, which led me to the error handling problem (which I thought was ok).
The following code is failing to connect to the database (as expected), but puts an error onto the screen and stops the page processing. It does not even output the ‘or die’ error text.
QUESTION: How can I just output a simple “Cant load data” message, and continue on normally?
function generateData()
{
global $post;
if ("$post->post_title" == "Home")
{
try
{
$myServer = "<servername>";
$myUser = "<username>";
$myPass = "<password>";
$myDB = "<dbName>";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't open database $myDB");
//... query processing here...
}
catch (Exception $e)
{
echo "Cannot load data<br />";
}
}
return $content;
}
Error being generated: (line 31 is $dbhandle = mssql_connect…)
Warning: mssql_connect() [function.mssql-connect]: Unable to connect to server: <servername> in <file path> on line 31
Fatal error: Maximum execution time of 30 seconds exceeded in <file path> on line 31
First of all, if
mssql_connectraises a warning when there’s a problem, there is not much you can do to avoid it : the only thing you could do is hide it, using the@operator :Note : you should not
die()when a connection error occurs : it’ll stop the execution of the whole application, which is most certainly not desired.The Fatal Error is a second problem *(which is probably a consequence of the first one)*.
Note that you cannot recover from a Fatal Error : it is Fatal. Which means you must avoid it, one way or another.
Here, the error is that your script is working for more than
max_execution_timeseconds ; as the error is reported on themssql_connectline, I suppose the script is waiting for the connection to succeed, and it doesn’t get etablished in less that 30 seconds.I don’t have an SQL Server database to test, but looking at the [Runtime Configuration][4] section of the manual for mssql, I’d say that these look interesting :
You could try changing those,
ini_set()before trying to connect.In the second case, something like this might do the trick :