Skip to content

Instantly share code, notes, and snippets.

@groovecoder
Created March 13, 2012 04:08
Show Gist options
  • Save groovecoder/2026673 to your computer and use it in GitHub Desktop.
Save groovecoder/2026673 to your computer and use it in GitHub Desktop.
a tiny crud/rest api in php
<?php
class db
{
protected static $dbh = false;
public function connect($dsn = null)
{
self::$dbh = new PDO($dsn);
self::$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
protected function fatal_error($exception)
{
throw $exception;
echo "<pre>Error!: $msg\n";
$bt = debug_backtrace();
foreach ($bt as $line) {
$args = var_export($line['args'], true);
echo "{$line['function']}($args) at {$line['file']}:{$line['line']}\n";
}
echo "</pre>";
die();
}
}
class table extends db
{
public function __construct($dsn, $tableName)
{
$this->dsn = $dsn;
$this->tableName = $tableName;
}
public function load($id="",$lx=-1,$ly=-1)
{
if (!self::$dbh) $this->connect($this->dsn);
if (strlen($id)) {
$id = self::$dbh->quote($id);
$where = "WHERE id=$id";
} else
$where = "";
if ($lx != -1)
$limit = "LIMIT $lx,$ly";
else
$limit = "";
try {
$sql = "SELECT * FROM " . $this->tableName . " $where $limit";
$rows = self::$dbh->query($sql)->fetchall(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
$this->fatal_error($e);
}
if (strlen($id) && count($rows)) return $rows[0];
return $rows;
}
public function save($record)
{
if ($record['id'] == null) return false;
if (!self::$dbh) $this->connect($this->dsn);
try {
$columns = array_keys($record);
$sql = "REPLACE INTO " . $this->tableName . " (" . implode(",", $columns) . ") VALUES (:" . implode(",:", $columns) . ")";
error_log("sql: $sql");
$stmt = self::$dbh->prepare($sql);
foreach ($columns as $column) {
$params[':'.$column] = $record[$column];
}
error_log(var_export($params, true));
$stmt->execute($params);
} catch (PDOException $e) {
$this->fatal_error($e);
return false;
}
return $this->load($record['id']);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment