Reputation: 23
I'm using a class for database connection, this class holds the CRUD methods, and also the database connection methods.
It's basically the core of all other classes that uses the DB.
I'm currently facing a problem on dealing with duplicate entry in unique columns, when inserting a record.
Database.class.php insertDB method:
class Database {
(...)
public function insertDB($sql,$params=null){
$con=$this->connect();
$query=$con->prepare($sql);
$query->execute($params);
$rs = $con->lastInsertId();
return $rs;
self::__destruct();
}
(...)
}
There is another class, PersonDAO.class.php, which is a class that inherits Database.class.
PersonDAO.class.php has its own method for inserting a record, which finally uses Database.class.php InsertBD method.
PersonDAO.class.php insert method: (notice it calls insertDB at the end).
class PersonDAO extends Database{
(...)
public function insert ($fields, $params=null) {
$numparams="";
for($i=0;$i<count($params);$i++) $numparams .= ",?";
$numparams=substr($numparams, 1);
$sql = "INSERT INTO Person ($fields) VALUES ($numparams)";
$t=$this->insertDB($sql,$params);
return $t;
}
(...)
}
The problem occurs in the registration form register.php, when I instantiate PersonDAO and use its insert method for inserting a duplicate entry into a column set as unique.
(...)
$person= new PersonDAO();
$fields="email,name";
$email="[email protected]"; //already existing record. email column set as unique
$name="John Doe";
$params=array($email,$name);
try {
$rs = $person->insert($fields,$params);
} catch (PDOException $e) {
if ($e->errorInfo[1] == 1062) {
echo "Cannot insert record. Duplicate entry";
}
}
(...)
It's not catching duplicate entry exception, as if there was no errors.
var_dump($rs) contains:
string(1) "0"
But should not it catch PDOException and print "Cannot insert record. Duplicate entry"?
Upvotes: 2
Views: 1363
Reputation: 88
Is there any "Uncaught Exception ..." message ? Perhaps, You first need to catch the Exception in your Database.class.php insertDB method and then throw it.
class Database {
(...)
public function insertDB($sql,$params=null){
try{
$con=$this->connect();
$query=$con->prepare($sql);
$query->execute($params);
$rs = $con->lastInsertId();
return $rs;
self::__destruct();
}
catch(Exception $e){
throw $e;
}
}
(...)
}
Or if there is no error at all. Check
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Upvotes: 1