简体   繁体   English

PHP PDO检查mysql错误

[英]PHP PDO check for mysql error

I have this problem that drives me crazy. 我有这个问题使我发疯。 All i want is just check a query for an error, if so display error, otherwise run the query. 我想要的只是检查查询是否有错误,如果显示则显示错误,否则运行查询。

I have the following almost (since it runs the insert query twice) working 我几乎有以下工作(因为它运行两次插入查询)

[..]

$dbdata = new mySQLAccessData();
$db = new PDO($dbdata->hostname,$dbdata->username,$dbdata->password);
$defaults = new Defaults();

[..]

if(!$db->exec($sql)){
    echo($defaults->throwError('MySql error',implode(":",$db->errorInfo())));
}else{
    $db->exec($sql);
    $defaults->writeLog($table,$db->lastInsertId(),'add');
}

I tried numerous things (amongst others the try(){}catch(){} method) but nothing worked except for the code above. 我尝试了很多方法(除了try(){}catch(){}方法之外),但是除了上面的代码外,其他方法都无效。 It shows the error the way i want, and only when an error occurs, but runs the exec() twice... 它以我想要的方式显示错误,并且仅在发生错误时显示,但运行exec()两次...

Can someone bail me out? 有人可以救我吗?

If you want to see an exception thrown when an error occurs, just set the PDO error-mode (see also: Connections and Connection management ): 如果您希望看到发生错误时引发的异常,只需设置PDO错误模式 (另请参见: 连接和连接管理 ):

$db = new PDO($dbdata->hostname,$dbdata->username,$dbdata->password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

This for example will make your code throw exceptions automatically. 例如,这将使您的代码自动引发异常。 Probably exactly what you're looking for. 可能正是您要找的东西。

The actual issue with your code is doing exec twice. 您的代码的实际问题是exec两次。 You don't need to: 您不需要:

$success = $db->exec($sql);

if (!$success) {
    echo $defaults->throwError('MySql error', implode(":", $db->errorInfo()));
} else {
    # do not exec *again* here.
    $defaults->writeLog($table, $db->lastInsertId(), 'add');
}

Why do you want to execute the query again in the else part? 为什么要在else部分再次执行查询? Usually you just try to run the query and if errors happen, react on them. 通常,您只是尝试运行查询,如果发生错误,请对它们作出反应。

[..]

$dbdata = new mySQLAccessData();
$db = new PDO($dbdata->hostname,$dbdata->username,$dbdata->password);
$defaults = new Defaults();

[..]

if(!$db->exec($sql)){
    echo($defaults->throwError('MySql error',implode(":",$db->errorInfo())));
}else{
    $defaults->writeLog($table,$db->lastInsertId(),'add');
}

As far as I know, there is no option to "test" a query before actually executing it. 据我所知,在实际执行查询之前没有选择“测试”查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM