I have done some research about using a databasewrapper for my data. However, I read some posts where people claim you shouldn't use PDO for a databasewrapper because it already is one.
That may be so, but I am still convinced that it has a lot of benefits.
- You handle all your data actions (crud) in one class, not spread across your website files. So it's much easier to debug and handle errors.
- You can easilly change your class with another databaseclass.
- You don't have to repeat your code, just call the code in the databaseclass
- Optionally you can extend the class with for example logging, statistic tests, ...
Example:
<?php
class Database
{
public $connection;
private $host = "";
private $username = "";
private $password = "";
private $dbname = "";
public function __construct(){
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbname",$this->username,$this->password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function insert($query, array $data){
$this->connection->prepare($query)->execute($data);
return $this->connection->lastInsertId();
}
public function update($query, array $data) {
$stmt = $this->executeQuery($query,$data);
return $stmt->rowCount();
}
public function delete($query, array $data) {
$stmt = $this->executeQuery($query,$data);
return $stmt->rowCount();
}
public function findOne($query, array $data = null){
$stmt = $this->executeQuery($query,$data);
return $stmt->fetchObject();
}
public function findMany($query, array $data = null){
$stmt = $this->executeQuery($query,$data);
return($stmt->fetchAll(PDO::FETCH_OBJ));
}
public function executeQuery($query,$data = null){
$stmt = $this->connection->prepare($query);
$stmt->execute($data);
return $stmt;
}
}
?>
Instead of constantly repeating all the steps for retrieving data, you can call get() and pass a query and some optional parameters. This is a lot more efficiƫnt than everytime open a connection, perform 3 lines of code and close it.
$db->get("select * from user where id = ?",array(1));