Last active
July 20, 2016 02:12
-
-
Save IgorHalfeld/a7875af80ac519534f3a6ee89417daf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Database { | |
private $pdo; | |
private $rowsNumber; | |
private $result; | |
public function __construct($host, $dbname, $user, $password) { | |
try { | |
$this->pdo = new PDO('mysql:dbname='.$dbname.';host='.$host, $user, $password); | |
} catch (PDOException $e) { | |
echo "Failed: " .$e->getMessage(); | |
} | |
} | |
private function eachValue($data) { | |
$fields = array(); | |
foreach ($data as $key => $value) { | |
$fields[] = $key .' = "'.addslashes($value). '"'; | |
} | |
return $fields; | |
} | |
/* | |
* Example | |
* ->sql('SELECT * FROM table_name') | |
*/ | |
public function query($sql) { | |
$query = $this->pdo->query($sql); | |
$this->rowsNumber = $query->rowCount(); | |
$this->result = $query->fetchAll(); | |
} | |
public function result() { | |
return $this->result; | |
} | |
public function rowsNumber() { | |
return $this->rowsNumber; | |
} | |
/* | |
* Example | |
* ->insert('table_name', array('name'=>'Halfeld')) | |
*/ | |
public function insert($table, $data) { | |
if(!empty($table) && (is_array($data) && count($data) > 0)) { | |
$sql = 'INSERT INTO '.$table.' SET '; | |
$fields = $this->eachValue($data); | |
$sql = $sql.implode(', ', $fields); | |
$this->pdo->query($sql); | |
} | |
} | |
/* | |
* Example | |
* ->update('table_name', array('name'=>'Halfeld'), array('id'=>'0'), 'OR') | |
*/ | |
public function update($table, $data, $where = array(), $condWhere = 'AND') { | |
if(!empty($table) && (is_array($data) && count($data) > 0) && is_array($where)) { | |
$sql = 'UPDATE '.$table.' SET '; | |
$fields = $this->eachValue($data); | |
$sql = $sql.implode(', ', $fields); | |
if(count($where) > 0) { | |
$fields = $this->eachValue($where); | |
$sql = $sql.' WHERE '.implode(' '.$condWhere.' ', $fields); | |
} | |
$this->pdo->query($sql); | |
} | |
} | |
/* | |
* Example | |
* ->delete('table_name', array('id'=>'10'), 'OR') | |
*/ | |
public function delete($table, $where, $condWhere = 'AND') { | |
if(!empty($table) && (is_array($where) && count($where) > 0)) { | |
$sql = 'DELETE FROM '.$table; | |
if(count($where) > 0) { | |
$fields = $this->eachValue($where); | |
$sql = $sql.' WHERE '.implode(' '.$condWhere.' ', $fields); | |
} | |
$this->pdo->query($sql); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment