PHP Try and Catch for SQL Insert

2019-01-23 23:52发布

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);
...

9条回答
\"骚年 ilove
2楼-- · 2019-01-24 00:48

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.

查看更多
Viruses.
3楼-- · 2019-01-24 00:50

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; 
}
查看更多
我只想做你的唯一
4楼-- · 2019-01-24 00:53
$new_user = new User($user);
$mapper = $this->spot->mapper("App\User");

try{
    $id = $mapper->save($new_user);     
}catch(Exception $exception){

    $data["error"] = true;
    $data["message"] = "Error while insertion. Erron in the query";
    $data["data"] = $exception->getMessage();

    return $response->withStatus(409)
    ->withHeader("Content-Type", "application/json")
    ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));        
}

if error occurs, you will get something like this->

{
    "error": true,
    "message": "Error while insertion. Erron in the query",
    "data": "An exception occurred while executing 'INSERT INTO \"user\" (...) VALUES (...)' with params [...]:\n\nSQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for integer: \"default\"" }

with status code:409.

查看更多
登录 后发表回答