views:

772

answers:

4

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);
...
+4  A: 

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
Yacoby
That Doesn't throw an error?
Byron Whitlock
I don't think mysql_query throws an exception.
Yacoby
Indeed, neither `mysql_query` nor `mysqli_query` throw an exception. `PDOStatement::execute` will, but only if you call `PDO::setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)` before calling `PDOStatement::execute`.
outis
A: 

Use a try catch block. That is standard for this type of thing. Get in the habit of using transactions or your data will eventually resemble alphabet soup.

try
{
   ...
}
 catch (Exception $e)
{
   log ($e->message);
    // possible rollback
}
Byron Whitlock
this does not work for me! the mysql functions do not throw exceptions.
Hippo
A: 

if you want to log the error etc you should use try/catch, if you dont; just put @ before mysql_query

edit : you can use try catch like this; so you can log the error and let the page continue to load

function throw_ex($er){  
  throw new Exception($er);  
}  
try {  
mysql_connect(localhost,'user','pass'); 
mysql_select_db('test'); 
$q = mysql_query('select * from asdasda') or throw_ex(mysql_error());  
}  
catch(exception $e) {
  echo "ex: ".$e; 
}
yasaluyari
mysql function are not throwing any exceptions.
Hippo
A: 

Use any method described in the previous post to somehow catch the mysql error.
Most common is:

$res = mysql_query('bla');
if ($res===false) {
  //error
  die();
}
//normal page

This would also work:

function error() {
  //error
  die()
}
$res = mysql_query('bla') or error();
//normal page

try { ... } catch {Exception $e) { .... } will not work!

Note: Not directly related to you question but I think it would much more better if you display something usefull to the user. I would never revisit a website that just displays a blank screen or any mysterious error message.

Hippo