问题
i am using this construct for checking the error why a statement is not executed:
$value1 = $username;
$value2 = $firstname;
$value3 = $lastname;
$sql = "INSERT INTO table (row1, row2, row3) VALUES (?, ? , ?)";
try {
$stmt = $dbh->prepare($sql);
$stmt->bindParam(1, $value1);
$stmt->bindParam(2, $value2);
$stmt->bindParam(3, $value3);
$stmt->execute();
} catch(PDOException $e) {
$var .= $e->getMessage();
}
include 'log.php';
log.php:
$logfile = fopen("logfile.txt", "a");
$error = date("d.m.Y H:i:s")." - ".$var.".\r\n";
fwrite($logfile, $error);
fclose($logfile);
there is no insert in my database and my log.php is empty as well, so i cant save the error, anybody could help me? greetings
回答1:
I have no idea why PDO errors attracts so distinct attention of PHP users. You would never see an include or an image manipulation so much nursed. But PDO statements, for some reason, always receive a special treatment.
While there is absolutely nothing special with PDO errors. That's exactly the same error as any other, and there is no need to treat PDO errors whatever special way. If a file was not found - PHP will log that error. If PDO query fails - PHP will log that error as well. Just tell PHP to do so.
ini_set('log_errors', 1);
is all you need. Then run your code and have an error logged
$sql = "INSERT INTO table (row1, row2, row3) VALUES (?, ? , ?)";
$stmt = $dbh->prepare($sql);
$stmt->execute(array($username, $firstname, $lastname));
来源:https://stackoverflow.com/questions/20749967/check-statement-error-pdo