Skip to content

Instantly share code, notes, and snippets.

@otarza
Created June 27, 2013 20:36
Show Gist options
  • Save otarza/5880159 to your computer and use it in GitHub Desktop.
Save otarza/5880159 to your computer and use it in GitHub Desktop.
Database interaction layer for PHP and MySql
<?php
/**
* Created by JetBrains PhpStorm.
* User: Otar
* Date: 2/22/13
* Time: 8:02 AM
* To change this template use File | Settings | File Templates.
*/
class DB {
private $pdo_connection;
function __construct() {
try {
$this->pdo_connection = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
$this->pdo_connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
} catch (PDOException $e) {
print "<div class='db-error error'>Error!: " . $e->getMessage() . "<br/></div>";
die();
}
}
public function select($query) {
$result = array();
$query = $this->pdo_connection->prepare($query);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$result[] = $row;
}
return $result;
}
/*
* Implements simple sql insert
*
* $table - table name to insert into
* $data - key => value array where keys are column names, values are data
*/
public function insert($table, $data) {
$result = array();
$columns = array();
$values = array();
foreach ($data as $column => $value) {
$columns[] = $column;
$values[] = $value;
}
$columns_imploded = implode(",", $columns);
$values_imploded = "'" . implode("','", $values) . "'";
$query = "INSERT INTO $table ($columns_imploded) VALUES($values_imploded)";
$query = $this->pdo_connection->prepare($query);
$result = $query->execute();
return $this->pdo_connection->lastInsertId();
}
/*
* Implements simple sql update
*
* $table - table name to update
* $where - string containing sql piece of where logic
* $data - key => value array where keys are column names, values are data
*/
public function update($table, $where, $data) {
$result = array();
$new_values = array();
foreach ($data as $column => $value) {
$new_values[] = $column . " = " . "'" . $value . "'";
}
$new_values_sql = join(",", $new_values);
$query = "UPDATE $table
SET $new_values_sql
WHERE $where ";
$query = $this->pdo_connection->prepare($query);
$result = $query->execute();
return $result;
}
/*
* Implements simple sql delete
*
* $table - table name where to delete
* $where - string containing sql piece of where logic
*/
public function delete($table, $where) {
$result = "";
$query = "DELETE FROM $table
WHERE $where ";
$query = $this->pdo_connection->prepare($query);
$result = $query->execute();
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment