Skip to content

Instantly share code, notes, and snippets.

@besingamkb
Last active August 29, 2015 14:07
Show Gist options
  • Save besingamkb/6caa6e104da719b7e64f to your computer and use it in GitHub Desktop.
Save besingamkb/6caa6e104da719b7e64f to your computer and use it in GitHub Desktop.
simple database class fit for simple CRUD application
<?php
/*******
database class personalize
author : besingamk
description: simple database class for simple CRUD application
driver : PDO
*/
class Database {
protected $host = "localhost";
protected $user = "root";
protected $pass = "";
protected $dbname = "login_db";
protected $conn;
private $sql_query;
private $where = array();
public function __construct() {
$this->conn = new PDO("mysql:host=" . $this->host .";dbname=" . $this->dbname, $this->user, $this->pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
public function query($query = null) {
$q = ($query == null) ? $query : $this->sql_query;
$this->sql_query = $query;
}
public function show_query() {
return $this->sql_query;
}
public function select($sql) {
$this->sql_query .= "SELECT $sql";
return $this;
}
public function from($table) {
$this->sql_query .= " FROM $table";
return $this;
}
public function where($field, $value, $cond = '=') {
$dilimeter = ( @$this->where['is_set'] != true) ? 'WHERE' : 'AND';
$this->where['is_set'] = true;
//echo $dilimeter;
$this->sql_query .= " " . $dilimeter . " $field $cond $value";
return $this;
}
public function order_by($field, $asc = 'ASC') {
$asc = (strtoupper($asc) != 'ASC') ? 'DESC' : 'ASC';
$this->sql_query .= " ORDER BY $field $asc";
return $this;
}
public function get() {
try {
$q = $this->conn->prepare($this->sql_query);
$q->execute();
$q->setFetchMode(PDO::FETCH_OBJ);
return $q->fetchAll();
} catch(PDOException $e) {
die("ERROR: ".$e->getMessage());
}
}
/*
below is the code for insert function
date 10-12-2014
*/
public function insert($table, $data) {
$new_data = array();
$fields = "";
$values = "";
foreach($data as $field_name => $value) {
$new_data[":" . $field_name] = $value;
$fields .= $field_name . ", ";
$values .= ":".$field_name . ", ";
}
$fields = substr($fields, 0, -2);
$values = substr($values, 0, -2);
try {
$sql = "INSERT INTO $table ($fields) VALUES ($values)";
$q = $this->conn->prepare($sql);
$q->execute($new_data);
} catch(PDOException $e) {
die('ERROR: ' . $e->getMessage());
}
}
/*
below is the code fo update function
date 10-12-2014
*/
public function update($data) {
// code goes here
}
}
$a = new Database();
//$a->query("SELECT * FROM users");
$a->select("id")->from("users")->where('ulevel', '1')->order_by('id');
echo $a->show_query();
echo "<pre>";
print_r($a->get());
// $data = array(
// 'username' => 'usersss',
// 'password' => md5('password')
// );
// //$a->insert('users', $data);
// $a->where("yow", "waysup");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment