Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Simple MySQLi abstraction layer into associative array
/*****************************| MYSQLI CONNECTION FUNCTION |*****************************/
* Simple MySQLi abstraction layer
* @param resource $mysqli The MySQLi connection link
* @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) {
if($mysqli->connect_errno) {
return array('info'=>array('error'=>'Connect failed: '.$mysqli->connect_error)); //error handling here
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...
if($res=$mysqli->prepare($query)) {
//dynamically bind all $v
if($v) {
for($i=1; $i<count($v); $i++) {
//bind all table rows to result
if(strtolower(substr($query,0,6))=="select") {
while($field=$meta->fetch_field()) {
//return associative array
while($res->fetch()) {
foreach($tempRow as $k=>$v2) $results["res"][$i][$k] = $v2;
else { //return infos about the query
if($o===1) { //adding debug infos
if($mysqli->warning_count) {
if($err=$mysqli->query("SHOW WARNINGS")) {
$results["info"]["error"].=$row[0].' ('.$row[1].'): '.$row[2];
for($i=1;$i<count($v);$i++) $q=preg_replace("/\?/",(substr($v[0],($i-1),1)=="s" ? '"' : '').$v[$i].(substr($v[0],($i-1),1)=="s" ? '"' : ''),$q,1);
if(strtolower(substr($query,0,6))=="update" || strtolower(substr($query,0,6))=="delete") { //optimize at update or delete
preg_match_all('/((update|delete) `(.*)` )/i',$query,$tables);
foreach($tables[3] as $t) $mysqli->query('OPTIMIZE TABLE '.$t);
return $results;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.