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':
case 'result':
return $result;
break;
default:
return $result;
break;
}
}
/* Get PDO istance to use it outside this class */
public function getPdo() { return $this->db; }
/* Disconnect from the database */
public function __destruct() { $this->db = NULL; }
}
Use
$db = new db;
$user = $db->smartQuery(array(
'sql' => "SELECT UserName FROM `post` WHERE UserUID = :uid",
'par' => array('uid' => $uid),
'ret' => 'fetch-assoc'
));
echo $user['Username'];
What I think is wrong
Well, I have encountered these 2 points while revisiting this code, and I'd like to get some feedback about them particularly:
- The error system (which, let's face it, sucks right now)
- The first
try-catch
code, which is actually working, but I never use that so, please, look at it.
Also if my application cannot connect to the database, most (if not all) features cannot be activated (such-as the PHP error log trough a database record, so that every times an error occurred, the admin is warned trough the application itself).