PHP Try和Catch for SQL Insert

mem*_*eme 24 php mysql error-handling performance

我的网站上有一个页面(高流量),每个页面加载都会插入一个页面.

我很好奇最快和最安全的方法(捕获错误)并继续,如果系统无法插入MySQL.我应该使用try/catch或die或其他东西.我想确保插入发生,但如果由于某种原因它不能我希望页面继续加载.

...
$db = mysql_select_db('mobile', $conn);
mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'") or die('Error #10');
mysql_close($conn);
...
Run Code Online (Sandbox Code Playgroud)

Yac*_*oby 25

检查文档显示它返回false错误.所以使用返回状态而不是or die().如果失败,它将返回false,您可以记录(或者您想要做的任何事情),然后继续.

$rv = mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'");
if ( $rv === false ){
     //handle the error here
}
//page continues loading
Run Code Online (Sandbox Code Playgroud)

  • 实际上,"mysql_query"和"mysqli_query"都没有抛出异常.`PDOStatement :: execute`将会,但只有在调用`PDOStatement :: execute`之前调用`PDO :: setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION)`. (8认同)

VKG*_*KGS 11

这可以做到这一点,

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());
}
Run Code Online (Sandbox Code Playgroud)


Nem*_*den 8

您可以自己在mysql查询失败时实现抛出异常.你需要的是为mysql_query函数编写一个包装器,例如:

// user defined. corresponding MySQL errno for duplicate key entry
const MYSQL_DUPLICATE_KEY_ENTRY = 1022;

// user defined MySQL exceptions
class MySQLException extends Exception {}
class MySQLDuplicateKeyException extends MySQLException {}

function my_mysql_query($query, $conn=false) {
    $res = mysql_query($query, $conn);
    if (!$res) {
        $errno = mysql_errno($conn);
        $error = mysql_error($conn);
        switch ($errno) {
        case MYSQL_DUPLICATE_KEY_ENTRY:
            throw new MySQLDuplicateKeyException($error, $errno);
            break;
        default:
            throw MySQLException($error, $errno);
            break;
        }
    }
    // ...
    // doing something
    // ...
    if ($something_is_wrong) {
        throw new Exception("Logic exception while performing query result processing");
    }

}

try {
    mysql_query("INSERT INTO redirects SET ua_string = '$ua_string'")
}
catch (MySQLDuplicateKeyException $e) {
    // duplicate entry exception
    $e->getMessage();
}
catch (MySQLException $e) {
    // other mysql exception (not duplicate key entry)
    $e->getMessage();
}
catch (Exception $e) {
    // not a MySQL exception
    $e->getMessage();
}
Run Code Online (Sandbox Code Playgroud)


eng*_*rdr 5

如果你想记录错误等,你应该使用try/catch,如果你不这样做; 只需在mysql_query之前放@

编辑:你可以像这样使用try catch; 这样您就可以记录错误并让页面继续加载

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; 
}
Run Code Online (Sandbox Code Playgroud)