Skip to content

Instantly share code, notes, and snippets.

@imvision
Last active December 23, 2015 06:19
Show Gist options
  • Save imvision/6593515 to your computer and use it in GitHub Desktop.
Save imvision/6593515 to your computer and use it in GitHub Desktop.
Simple database abstraction for mysql queries TODO: Add support for joins
<?php
/**
* abstraction for mysql SELECT query
*/
function qry( $table, $columns, $where = "" ) {
$output = array();
$qry = "SELECT $columns FROM $table";
if ( $where != "" ) {
$qry = $qry . " WHERE " . $where;
}
$res = mysql_query($qry);
if (mysql_num_rows($res) > 0 )
{
while($row = mysql_fetch_assoc($res)) {
$output[] = $row;
}
}
return $output;
}
/**
* abstraction for mysql UPDATE query
*/
function update($table, $data_array, $where) {
if ( count($data_array) < 1 )
return false;
$qry = "UPDATE $table SET ";
$delimit = "";
foreach( $data_array as $key => $val ) {
$qry .= $delimit . "`" . $key . "` = '$val' ";
$delimit = ",";
}
if ( $where != "" ) {
$qry = $qry . " WHERE " . $where;
}
mysql_query($qry);
return true;
}
/**
* function abstraction for mysql INSERT query
*/
function addNew($table, $data_array) {
$qry = "INSERT INTO $table (";
$delimit = "";
$val = " VALUES (";
foreach( $data_array as $col => $value ) {
$qry .= "{$delimit} {$col}";
$val .= "{$delimit} '{$value}'";
$delimit = ",";
}
$qry .= ")";
$val .= ")";
$qry .= $val;
mysql_query($qry);
return mysql_insert_id();
}
<?php
function dbSafe($data) {
if(is_array($data)) {
$new = array();
foreach($data as $k => $v) {
$new[$k] = $v;
}
} else {
$new = dbSafe($data);
}
return $new;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment