I have a page on my website (high traffic) that does an insert on every page load.
I am curious of the fastest and safest way to (catch an error) and continue if the system is not able to do the insert into MySQL. Should I use try/catch or die or something else. I want to make sure the insert happens but if for some reason it can't I want the page to continue to load anyway.
... $db = mysql_select_db('mobile', $conn); mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10'); mysql_close($conn); ...
The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.
The error / mysqli_error() function returns the last error description for the most recent function call, if any.
PHP error handling keywords Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception. Catch: This block of code will be called only if an exception occurs within the try code block.
A TRY... CATCH construct catches all execution errors that have a severity higher than 10 that do not close the database connection. A TRY block must be immediately followed by an associated CATCH block. Including any other statements between the END TRY and BEGIN CATCH statements generates a syntax error.
Checking the documentation shows that its returns false
on an error. So use the return status rather than or die()
. It will return false if it fails, which you can log (or whatever you want to do) and then continue.
$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'"); if ( $rv === false ){ //handle the error here } //page continues loading
This can do the trick,
function createLog($data){ $file = "Your path/incompletejobs.txt"; $fh = fopen($file, 'a') or die("can't open file"); fwrite($fh,$data); fclose($fh); } $qry="INSERT INTO redirects SET ua_string = '$ua_string'" $result=mysql_query($qry); if(!$result){ createLog(mysql_error()); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With