Skip to content

Instantly share code, notes, and snippets.

@Terrance
Created April 1, 2013 11:40
Show Gist options
  • Save Terrance/5284490 to your computer and use it in GitHub Desktop.
Save Terrance/5284490 to your computer and use it in GitHub Desktop.
Wrapper class for SQL database connections. Helper methods for fetching, adding, editing and deleting data.
<?
class DB {
private static $conn = null;
public static function connect($host="localhost", $user="root", $pass=null, $db=null) {
DB::$conn = mysqli_connect($host, $user, $pass, $db);
}
public static function insert($table, $data) {
if (!DB::$conn) {
DB::connect();
}
$rows = array_keys($data);
$vals = array_values($data);
foreach ($vals as $i => $val) {
switch (gettype($val)) {
case "integer":
case "double":
case "boolean":
$vals[$i] = (string) $val;
break;
case "string":
$vals[$i] = "\"" . $val . "\"";
break;
}
}
$result = mysqli_query(DB::$conn, "INSERT INTO `" . $table . "` (`" . implode("`, `", $rows) . "`) VALUES (" . implode(", ", $vals) . ");");
return $result;
}
public static function fetch($table, $where=null) {
if (!DB::$conn) {
DB::connect();
}
$result = mysqli_query(DB::$conn, "SELECT * FROM `" . $table . "`" . ($where ? " WHERE " . $where : "") . ";");
$data = array();
if ($result) {
$count = 0;
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
$count++;
}
}
return $data;
}
public static function error() {
return mysqli_error(DB::$conn);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment