<?php
/**
 *	Database Functions
 *  --------------
 *	Description : MySQli DB Functions
 *	Written by  : Kyriazis
 *	Version     : 1.0.0
 *  Created     : 09/07/2015
 *  Updated	    : 
 *	
 **/
      
    function database_query($mysqli, $sql, $return_type = DATA_ONLY, $first_row_only = ALL_ROWS, $fetch_func = FETCH_ASSOC, $debug = false)
    {
    	$data_array = array();
    	$num_rows = 0;
    	$fields_len = 0;
    	
    	$result = mysqli_query($mysqli, $sql);
    	if($debug == true) echo $sql . '-' . mysqli_error($mysqli);
    	if($result){
    		if($return_type == 0 || $return_type == 2){
    			while($row_array = $fetch_func($result)){
    				if(!$first_row_only){
    					array_push($data_array, $row_array);
    				}else{
    					$data_array = $row_array;
    					break;
    				}
    			}
    		}		
    		
    		$num_rows = mysqli_num_rows($result);
    		$fields_len = mysqli_num_fields($result);
    		mysqli_free_result($result);
    	}
    	
    	switch($return_type){
    		case DATA_ONLY:
    			return $data_array;
    		case ROWS_ONLY:
    			return $num_rows;
    		case DATA_AND_ROWS:
    			return array($data_array, $num_rows);
    		case FIELDS_ONLY:
    			return $fields_len;
    	}	
    }


    function database_void_query($mysqli, $sql, $debug = false, $zero_affected = true)
    {
        $result = mysqli_query($mysqli , $sql);	
    	if($debug == true) echo $sql . ' - ' . mysqli_error($mysqli);
    	$affected_rows =  mysqli_affected_rows($mysqli);
    	if(preg_match('/update /i', $sql)){
    		if($zero_affected && $affected_rows >= 0) return true;
    		if(!$zero_affected && $affected_rows > 0) return true;
    	}else if(preg_match('/drop t/i', $sql)){
    		if($affected_rows >= 0) return true;
    	}else if(preg_match('/create t/i', $sql)){
    		if($affected_rows >= 0) return true;
    	}else if($affected_rows > 0){ 
    		return true;
    	}
    	return false;
    }

?>