Skip to content

Instantly share code, notes, and snippets.

@bharathraj-e
Last active August 25, 2020 05:14
Show Gist options
  • Save bharathraj-e/5e89031fcc508c420ad04b085990bdd6 to your computer and use it in GitHub Desktop.
Save bharathraj-e/5e89031fcc508c420ad04b085990bdd6 to your computer and use it in GitHub Desktop.
PHP DB CRUD CLASS - API Based Structure
<?php
require_once __DIR__ . '/response.php';
require_once __DIR__ . '/db.php';
class CRUD
{
private $db;
public function __construct()
{
$this->db = db();
}
private function _getBinders(array $params = array()): array
{
$bind = '';
foreach ($params as $param) {
$type = gettype($param);
if ($type == 'double') $bind .= 'd';
else if ($type == 'integer') $bind .= 'd';
else $bind .= 's';
}
$a_params[] = $bind;
for ($i = 0; $i < count($params); $i++) {
$a_params[] = $params[$i];
}
return $a_params;
}
public function select(string $query, array $params = array()): array
{
try {
$stmt = $this->db->prepare($query);
if (count($params) > 0) {
$temp = $this->_getBinders($params);
$binder = array();
for ($i = 0; $i < count($temp); $i++) {
$binder[] = &$temp[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $binder);
}
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
} catch (\Throwable $th) {
err($th->getMessage());
} catch (\Error $e) {
err($e->getMessage());
} catch (\Exception $e) {
err($e->getMessage());
}
return $data;
}
public function insert(string $query, array $params = array()): int
{
$insertId = 0;
try {
$stmt = $this->db->prepare($query);
if (count($params) > 0) {
$temp = $this->_getBinders($params);
$binder = array();
for ($i = 0; $i < count($temp); $i++) {
$binder[] = &$temp[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $binder);
}
$stmt->execute();
$insertId = $stmt->insert_id;
$stmt->close();
} catch (\Throwable $th) {
err($th->getMessage());
} catch (\Error $e) {
err($e->getMessage());
} catch (\Exception $e) {
err($e->getMessage());
}
return $insertId;
}
public function update(string $query, array $params = array()): int
{
$affectedRows = 0;
try {
$stmt = $this->db->prepare($query);
if (count($params) > 0) {
$temp = $this->_getBinders($params);
$binder = array();
for ($i = 0; $i < count($temp); $i++) {
$binder[] = &$temp[$i];
}
call_user_func_array(array($stmt, 'bind_param'), $binder);
}
$stmt->execute();
$affectedRows = $stmt->affected_rows;
$stmt->close();
} catch (\Throwable $th) {
err($th->getMessage());
} catch (\Error $e) {
err($e->getMessage());
} catch (\Exception $e) {
err($e->getMessage());
}
return $affectedRows;
}
public function __destruct()
{
if ($this->db != null) {
$this->db->close();
}
}
}
<?php
require_once __DIR__ . '/response.php';
function db(): \mysqli
{
try {
$db = mysqli_connect('server', 'username', 'password', 'database');
} catch (\Throwable $th) {
err('Connection error');
} catch (\Error $e) {
err($e->getMessage());
} catch (\Exception $e) {
err($e->getMessage());
}
return $db;
}
<?php
function err(string $err): void
{
$res = array();
$res['ok'] = false;
$res['err'] = $err;
_finish($res);
}
function complete($data): void
{
$res = array();
$res['ok'] = true;
$res['data'] = $data;
_finish($res);
}
function _finish(array $res): void
{
header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Pragma: no-cache');
header('Content-Type: application/json');
echo json_encode($res, JSON_PRETTY_PRINT);
die();
}
@bharathraj-e
Copy link
Author

bharathraj-e commented Aug 23, 2020

Example 1:

<?php

require_once __DIR__ . 'db-crud.php';

$db = new CRUD;

$data = $db->select('SELECT * FROM products');

complete($data);

@bharathraj-e
Copy link
Author

bharathraj-e commented Aug 23, 2020

Example 2:

<?php

require_once __DIR__ . 'db-crud.php';

$db = new CRUD;

$id = $db->insert(
    'INSERT INTO products(product_id, purchase_date, bill_no, total_price) VALUES (?,?,?,?)',
    [
        $productId,
        $purchaseDate,
        $billNo,
        $total,
    ]
); //returns insert id

complete($id); 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment