When it comes to database operations in PHP, PDO provides a lot of advantages. PDO is a database access tool in PHP that enables uniform access across multiple databases, Error handling and security.
As a developer, I used the PHP wrapper class where I can manage my query function from one place. Here is the PDO wrapper class in PHP.
dbconfig.php
<?php
//DB Params
define('DBHOST', 'localhost');
define('DBUSER', 'root');
define('DBPASS', '');
define('DBNAME', 'mydb');
?>
Database.php
<?php
class Database {
private $host = DBHOST;
private $user = DBUSER;
private $pass = DBPASS;
private $dbname = DBNAME;
private $dbh;
private $error;
private $stmt;
public function __construct() {
// Set DSN
$dsn = 'mysql:host=' . $this->host . ';charset=utf8mb4;dbname=' . $this->dbname;
// Set options
$options = array (
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_BOTH,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a new PDO instance
try {
$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
}
// Catch any errors
catch (PDOException $e ) {
$this->error = $e->getMessage();
}
}
public function query($query) {
try {
$this->stmt = $this->dbh->prepare($query);
}
catch ( PDOException $e ) {
//return error message with SQL statement
//$this->error = $e->getMessage();
echo '<div class="alert alert-danger"><strong>Error! </strong>'.$this->error = $e->getMessage().'<br>'.$query.'</div>';
}
}
//$this->stmt = $this->dbh->prepare($query);
public function bind($param, $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 ( $param, $value, $type );
}
public function execute(){
//return $this->stmt->execute();
try {
return $this->stmt->execute();
}
catch ( PDOException $e ) {
echo '<div class="alert alert-danger"><strong>Error! </strong>'.$this->error = $e->getMessage().'</div>';
}
}
public function resultSet(){
$this->execute();
return $this->stmt->fetchAll();
}
public function single(){
$this->execute();
return $this->stmt->fetch();
}
public function rowCount(){
return $this->stmt->rowCount();
}
public function lastInsertId(){
return $this->dbh->lastInsertId();
}
public function beginTransaction(){
return $this->dbh->beginTransaction();
}
public function endTransaction(){
return $this->dbh->commit();
}
public function cancelTransaction(){
return $this->dbh->rollBack();
}
public function debugDumpParams(){
return $this->stmt->debugDumpParams();
}
public function close(){
$this->dbh = null;
}
}
Here is CRUD example:
//Call the class
require_once('dbconfig.php');
require_once('Database.php');
$db = new Database;
//Create data
$customerEmail = 'info@test.com'; // or $_POST['customer_email'];
$addCustSql = "INSERT INTO mytable (customer_email) VALUES (:customerEmail)";
$db->query($addCustSql);
$db->bind(":customer_email", $customerEmail);
$db->execute();
echo $db->lastInsertId();
//Read
$custInfoSql = "SELECT * FROM customers WHERE customer_id = :customerId";
$db->query($custInfoSql);
$db->bind(":customer_id", "1");
$result = $db->single();
echo $db->rowCount();
//print_r($result);
echo $customerEmail = $result["customer_email"];
//Read (All)
$custInfoSql = "SELECT * FROM customers";
$db->query($custInfoSql);
$results = $db->resultSet();
echo $db->rowCount();
foreach ($results as $row)
{
echo $customerEmail = $result["customer_email"];
}
//Read with WHERE
$custInfoSql = "SELECT * FROM customers WHERE lname=:lname";
$db->query($custInfoSql);
$db->bind(":lname", "John");
$results = $db->resultSet();
echo $db->rowCount();
foreach ($results as $row)
{
echo $customerEmail = $result["customer_email"];
}
//Update data
$customerId =1; // or $_POST['customer_id'];
$customerEmail = 'info@test.com'; //$_POST['customer_email'];
$updateCustSql ="UPDATE customers SET customer_email=:customerEmail WHERE customer_id =:customerId";
$db->query($updateCustSql);
$db->bind(':customer_id', $customerId);
$db->bind(':customerEmail', $customerEmail);
$db->execute();
//Delete data
$delCustSql = "DELETE FROM customers WHERE customer_id=:customerId";
$db->query($delCustSql);
$db->bind(':customer_id', $customerId);
$db->execute();
//Transcation
$db->beginTransaction();
$db->query("INSERT INTO mytable (customer_email) VALUES (:customerEmail)");
//first data
$db->bind(":customer_email", "info@test.com");
$db->execute();
//second data
$db->bind(":customer_email", "info@example.com");
$db->execute();
$db->endTransaction();