patternphpMinor
Database class using PDO
Viewed 0 times
databaseclassusingpdo
Problem
The point of this question
I'm actually using it while developing a simple application and it seems to cover all my needs. Also it uses PDO so that we don't really have to worry about SQL Injection. I know I usually code strange, but I hope you could give me suggestions and feedback in order to improve it.
Code: Database Class
```
/ Operate on the database using our super-safe PDO system /
class db
{
/ PDO istance /
private $db = NULL;
/ Number of the errors occurred /
private $errorNO = 0;
/ Connect to the database, no db? no party /
public function __construct()
{
try
{
$this->db = new PDO(
'mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host'), reg::get('db-username'), reg::get('db-password')
);
}
catch (Exception $e)
{
exit('App shoutdown');
}
}
/ Have you seen any errors recently? /
public function getErrors() { return ($this->errorNO > 0) ? $this->errorNO : false; }
/ Perform a full-control query /
public function smartQuery($array)
{
# Managing passed vars
$sql = $array['sql'];
$par = (isset($array['par'])) ? $array['par'] : array();
$ret = (isset($array['ret'])) ? $array['ret'] : 'res';
# Executing our query
$obj = $this->db->prepare($sql);
$result = $obj->execute($par);
# Error occurred...
if (!$result) { ++$this->errorNO; }
# What do you want me to return?
switch ($ret)
{
case 'obj':
case 'object':
return $obj;
break;
case 'ass':
case 'assoc':
case 'fetch-assoc':
return $obj->fetch(PDO::FETCH_ASSOC);
break;
case 'all':
case 'fetch-all':
return $obj->fetchAll();
break;
case 'res':
ca
I'm actually using it while developing a simple application and it seems to cover all my needs. Also it uses PDO so that we don't really have to worry about SQL Injection. I know I usually code strange, but I hope you could give me suggestions and feedback in order to improve it.
Code: Database Class
```
/ Operate on the database using our super-safe PDO system /
class db
{
/ PDO istance /
private $db = NULL;
/ Number of the errors occurred /
private $errorNO = 0;
/ Connect to the database, no db? no party /
public function __construct()
{
try
{
$this->db = new PDO(
'mysql:dbname='.reg::get('db-name').';host='.reg::get('db-host'), reg::get('db-username'), reg::get('db-password')
);
}
catch (Exception $e)
{
exit('App shoutdown');
}
}
/ Have you seen any errors recently? /
public function getErrors() { return ($this->errorNO > 0) ? $this->errorNO : false; }
/ Perform a full-control query /
public function smartQuery($array)
{
# Managing passed vars
$sql = $array['sql'];
$par = (isset($array['par'])) ? $array['par'] : array();
$ret = (isset($array['ret'])) ? $array['ret'] : 'res';
# Executing our query
$obj = $this->db->prepare($sql);
$result = $obj->execute($par);
# Error occurred...
if (!$result) { ++$this->errorNO; }
# What do you want me to return?
switch ($ret)
{
case 'obj':
case 'object':
return $obj;
break;
case 'ass':
case 'assoc':
case 'fetch-assoc':
return $obj->fetch(PDO::FETCH_ASSOC);
break;
case 'all':
case 'fetch-all':
return $obj->fetchAll();
break;
case 'res':
ca
Solution
A few things.
When you connect, don't hard code mysql, you are already fetching all the db info from a registry/config ... make the the dbtype configurable as well. That is after all, the point of PDO.
When you catch errors in connection or when executing a query, use the PDOException class
use exceptions for your prepare and execute calls instead of counting the errors that happens...as that's not really useful (it will be obvious an error happened, what I care about is what that error actually is).
personally, I would break down this class into specific methods. instead of connecting to the db in the constructor, I would have a connect() method to do this. I would also have a query, prepare, and bind method and then have interaction method: delete, update, insert and then a set of fetch methods, fetchOne, fetchAll, fetchCol, etc.
Also the connect method would check for a set conn, and only attempt to connect if you didn't already have an existing connection. The query method would call connect(). The reason for this is that you may include your db class throughout your code, even if you dont fetch anything in particular requests...with your code if this is the case a connection will be made regardless. What you want is lazy loading...meaning a db connection will only be made if you actually attempt to use the db with a fetch/update/delete/insert/etc.
Here is some sample pseudo code
When you connect, don't hard code mysql, you are already fetching all the db info from a registry/config ... make the the dbtype configurable as well. That is after all, the point of PDO.
When you catch errors in connection or when executing a query, use the PDOException class
use exceptions for your prepare and execute calls instead of counting the errors that happens...as that's not really useful (it will be obvious an error happened, what I care about is what that error actually is).
personally, I would break down this class into specific methods. instead of connecting to the db in the constructor, I would have a connect() method to do this. I would also have a query, prepare, and bind method and then have interaction method: delete, update, insert and then a set of fetch methods, fetchOne, fetchAll, fetchCol, etc.
Also the connect method would check for a set conn, and only attempt to connect if you didn't already have an existing connection. The query method would call connect(). The reason for this is that you may include your db class throughout your code, even if you dont fetch anything in particular requests...with your code if this is the case a connection will be made regardless. What you want is lazy loading...meaning a db connection will only be made if you actually attempt to use the db with a fetch/update/delete/insert/etc.
Here is some sample pseudo code
$db = new MyPdoClass();
$db->connect();
$stmt = $db->query($sql, $params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// or call your MyPdoClass::fetchAll, which would do that so you would just call
$results = $db->fetchAll($sql, $params);Code Snippets
$db = new MyPdoClass();
$db->connect();
$stmt = $db->query($sql, $params);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
// or call your MyPdoClass::fetchAll, which would do that so you would just call
$results = $db->fetchAll($sql, $params);Context
StackExchange Code Review Q#602, answer score: 5
Revisions (0)
No revisions yet.