Reputation: 324
I am trying to learn about using the PDO method to access mysql databases. In the following code sample I have created a test program which works fine when there is no exception. To generate an exception I added a mandatory third field to the table so that the execute statement would fail. What I am hoping to do is test the 'catch' branch, but after trying several different thing I always get an 'uncaught exception error' from that line, eg.:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 1364 Field 'Tst_integer' doesn't have a default value' in /var/www/ccc/ccc/cccccy/zztest.php:46
Line 46 corresponds to the execute statement.
Why is the exception not triggered?
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
class pdo_connect {
var $pdo_con;
var $message;
function __construct(){
$cur_date = date('Y-m-d H:i:s');
$BDconfig = array(
'host' => 'localhost',
'user' => 'p2p_user',
'pass' => 'keith1',
'dbname' => 'p2p_notes_data'
);
$db_host = $BDconfig['host'];
$db_user = $BDconfig['user'];
$db_pass = $BDconfig['pass'];
$db_name = $BDconfig['dbname'];
$dsn = 'mysql:dbname='. $db_name . ';' . 'host=' . $db_host;
// mysql connect information, pass
try{
$this->pdo_con = new PDO ($dsn, $db_user, $db_pass);
$this->pdo_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$this->pdo_con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (\PDOException $e) {
echo '$cur_date' . " " . 'Connection failed: ' . $e->getMessage() . PHP_EOL;
die();
}
}
function __destruct(){
$this->pdo_con = null;
}
}
$dbh = new pdo_connect;
//$dbh->pdo_con->beginTransaction();
$field1 = date('Y-m-d H:i:s');
$field2 = 'mytst';
$sth = $dbh->pdo_con->prepare("INSERT INTO test_table (Tst_Date,Tst_String) VALUES (:field1,:field2);");
try {
$sth->execute(array(":field1" => $field1, ":field2" => $field2));
} catch (PDOExeption $e) {
//$dbh->pdo_con->rollBack();
echo $e->getMessage();
echo 'ttttt', PHP_EOL;
}
//$dbh->pdo_con->commit();
?>
Upvotes: 1
Views: 266