Skip to content

Instantly share code, notes, and snippets.

@dominikwilkowski
Created July 15, 2014 04:03
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 dominikwilkowski/19ac1947a6100851887f to your computer and use it in GitHub Desktop.
Save dominikwilkowski/19ac1947a6100851887f to your computer and use it in GitHub Desktop.
MySQL replacement
<?php
/*****************************| MYSQL CONNECTION FUNCTION |*****************************/
/**
* Simple MySQL abstraction layer for the MySQLi absctration as a replacement
*
* @param resource $mysqli The MySQLi connection link for upgrade to MySQLi
* @param string $query The MySQL query for prepaired statement
* @param array $v The parameters to replace ? in $query. First element must be the type
* @param integer $o Option for more debug infos [0]=no infos(default) [1]=adding debug infos
*
* @return array [for select]=associative array of table result [for everything else]=associative array with affectedRows,info and insertID
*/
function connectDB($mysqli,$query,$v=array(),$o=0) {
$results=array();
if(substr_count($query,"?")!=strlen($v[0]) || strlen($v[0])!=((count($v)-1)>=0 ? (count($v)-1) : 0)) {
return array('info'=>array('error'=>'Placeholders are unequal! placeholders:'.substr_count($query,"?").', replacements:'.strlen($v[0]).', param:'.(count($v)-1).' ('.$v[0].')')); //error handling here...
exit();
}
$q=$query;
for($i=1;$i<count($v);$i++) {
$q=preg_replace("/\?/",(substr($v[0],($i-1),1)=="s" ? '"' : '').'tempplaceholder'.$i.(substr($v[0],($i-1),1)=="s" ? '"' : ''),$q,1);
${"tempplaceholder".$i}=mysql_real_escape_string($v[$i]);
$q=str_replace('tempplaceholder'.$i,${"tempplaceholder".$i},$q);
}
if(strtolower(substr($q,0,6))=="select") {
$MySqlres=mysql_query($q);
if($MySqlres) while($qRes=mysql_fetch_array($MySqlres)) {
$results["res"][]=$qRes;
}
}
else {
$results["info"]["affectedRows"]=mysql_query($q);
$results["info"]["insertID"]=mysql_insert_id();
}
if($o===1) { //adding debug infos
$results["info"]["query"]=$q;
$results["info"]["param"]=json_encode($v);
}
if(strtolower(substr($query,0,6))=="update" || strtolower(substr($query,0,6))=="delete") { //optimize at update and delete
preg_match_all('/((update|delete) `(.*)` )/i',$query,$tables);
foreach($tables[3] as $t) mysql_query('OPTIMIZE TABLE `'.$t.'`');
}
return $results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment