Skip to content

Instantly share code, notes, and snippets.

@johnvilsack
Created December 8, 2011 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnvilsack/1447900 to your computer and use it in GitHub Desktop.
Save johnvilsack/1447900 to your computer and use it in GitHub Desktop.
<?php
class CRUD {
private $DB;
public function __set($name, $v) {
switch ($name) {
case 'username':
$this->username = $v;
break;
case 'password':
$this->password = $v;
break;
case 'database':
$this->database = $v;
break;
default:
throw new Exception("$name is invalid");
}
}
public function ConnectDB() {
isset($this->username);
isset($this->password);
if (!$this->DB instanceof PDO) {
$this->DB = new PDO($this->database, $this->username, $this->password);
$this->DB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
public function SQLWithReturn($sql) {
$this->ConnectDB();
return $this->DB->query($sql);
}
public function SQLNoReturn($sql) {
$this->ConnectDB();
$this->DB->query($sql);
}
// CREATE
public function InsertDB($table, $v) {
$this->ConnectDB();
$keys = array_keys($v[0]);
$sql = "INSERT INTO $table";
$fields = '( ' . implode(' ,', $keys) . ' )';
$bound = '(:' . implode(', :', $keys) . ' )';
$sql .= $fields . ' VALUES ' . $bound;
$query = $this->DB->prepare($sql);
foreach ($v as $vals) {
$query->execute($vals);
}
}
// READ
public function SelectDB($table, $field = null, $id = null) {
$this->ConnectDB();
$statement = "SELECT * FROM `$table` WHERE `$field`=:id";
$query = $this->DB->prepare($statement);
$query->bindParam(':id', $id);
$query->execute();
return $query->fetchAll(PDO::FETCH_ASSOC);
}
// UPDATE
public function UpdateDB($table, $field, $value, $target, $id) {
$this->ConnectDB();
$sql = "UPDATE `$table` SET `$field`='{$value}' WHERE `$target` = :id";
$query = $this->DB->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$query->execute();
}
// DELETE
public function DeleteDB($table, $field, $id) {
$this->ConnectDB();
$sql = "DELETE FROM `$table` WHERE `$field` = :id";
$query = $this->DB->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_STR);
$query->execute();
}
public function QuickerLoop($query) {
foreach($this->DB->query($query) as $row) {
echo $row['animal_id'];
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment