Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save MakkiAbid/9ff72fc3e94a7844faed074d00744d68 to your computer and use it in GitHub Desktop.
Save MakkiAbid/9ff72fc3e94a7844faed074d00744d68 to your computer and use it in GitHub Desktop.
PDO Based CRUD operations in PHP
<?php
class DataBase
{
protected $connection;
public function __construct($host, $db, $user, $pass, $charset = 'utf8mb4', $options = []){
$options = array_merge([
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
], $options);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$this->connection = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
throw new \PDOException($e->getMessage(), (int)$e->getCode());
}
}
public function getData($table, $column, $value){
$data = $this->connection->prepare(sprintf("SELECT * FROM %s WHERE %s = ?", $table, $column));
$data->execute([$value]);
return $data->fetch();
}
public function insert($table, $data){
$columns = implode(', ', array_keys($data));
$placeholders = implode(', ', array_fill(0, count($data), '?'));
$query = sprintf("INSERT INTO `%s` (%s) VALUES (%s)", $table, $columns, $placeholders);
$values = array_values($data);
$stmnt = $this->connection->prepare($query);
$stmnt->execute($values);
return true;
}
public function delete($table, $column, $value) {
$query = sprintf("DELETE FROM `%s` WHERE (%s) = %s", $table, $column, $value);
$stmnt = $this->connection->prepare($query);
$stmnt->execute([$value]);
return true;
}
public function update($table, $data, $cond){
$set_statement = "";
foreach($data as $key => $value){
$set_statement .= sprintf("`%s` = ?, ", $key);
}
$set_statement = rtrim($set_statement, ', ');
$query = sprintf("UPDATE `%s` SET %s WHERE `id` = %u", $table, $set_statement, $cond);
return $query;
}
}
<?php
$host = 'SERVER';
$db = 'DBNAME';
$user = 'USERNAME';
$pass = 'PASSWORD';
$charset = 'utf8mb4';
$db = new DataBase($host, $db, $user, $pass);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment