Reputation: 123
I have a PDO Database Class, I'm a little new to PDO so I don't know how I would go about returning errors so I can debug if something goes wrong. I just want to know the best methods of going about catching errors and returning them back to the request. Here is my database class:
class database {
private $dbh;
private $stmt;
public function __construct($user, $pass, $dbname) {
$this->dbh = new PDO(
"mysql:host=localhost;dbname=$dbname",
$user,
$pass,
array( PDO::ATTR_PERSISTENT => true )
);
}
public function query($query) {
$this->stmt = $this->dbh->prepare($query);
return $this;
}
public function bind($pos, $value, $type = null) {
if( is_null($type) ) {
switch( true ) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->stmt->bindValue($pos, $value, $type);
return $this;
}
public function execute() {
return $this->stmt->execute();
}
public function resultset() {
$this->execute();
return $this->stmt->fetchAll();
}
public function single() {
$this->execute();
return $this->stmt->fetch();
}
}
Thanks
Upvotes: 0
Views: 187
Reputation: 1373
You can catch error in your "client code". Use try/catch blocks in every call that involves "execute" or "query" methods. Then you can head your application as you want whenever an error happens.
Upvotes: 1