简体   繁体   中英

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. It shows the error the way i want, and only when an error occurs, but runs the exec() twice...

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 ):

$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. 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? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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