Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Try and Catch for SQL Insert

Tags:

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); ... 
like image 951
meme Avatar asked Dec 16 '09 23:12

meme


People also ask

Is there a try-catch in PHP?

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.

How can I get SQL error in PHP?

The error / mysqli_error() function returns the last error description for the most recent function call, if any.

How can I get database exception in PHP?

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.

What is the try and catch method in SQL?

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.


2 Answers

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 
like image 65
Yacoby Avatar answered Oct 07 '22 18:10

Yacoby


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()); } 
like image 28
vkGunasekaran Avatar answered Oct 07 '22 20:10

vkGunasekaran