setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); $DB->query('SET NAMES \'utf8\''); function db_select($table, $data, $where=[], $order=[], $join=[], $debug=false) { global $DB; $STH = ""; if(gettype($data)=='string') $data = array($data); $data = '`'.implode('`,`', $data).'`'; $data = str_replace('`*`','*', $data); if(!empty($where) && is_array($where)) { $cond = []; foreach($where as $key=>$value) { $cond[] = "`$key`='$value'"; } $where = implode(' AND ', $cond); $where = str_replace('=\'!', '!=\'',$where); $where = str_replace('AND `|', 'OR `', $where); $where = preg_replace('#=\s*[\'\"]([<>=]+)(.*?)[\'\"]#', '$1 \'$2\'', $where); } if(!empty($order) && is_array($order)) { // format: ['field1'=>'direction','field2'=>'direction'...] OR ['field1', 'field2'...] $cond = []; foreach($order as $field=>$direction) { if(is_numeric($field)) { $field = $direction; $direction='ASC'; } $cond[] = $field.' '.$direction; } $order = implode(',',$cond); } if(!empty($join) && is_array($join)) { // format: ['table1'=>['field-of-source','field-of-table1'], 'table2'=>['field-of-source','field-of-table2']] $cond = []; foreach($join as $key=>$value) { if(is_array($value) && count($value)==2) { $cond[] = str_replace('~', $key, ' JOIN '.$key.' ON '.$table.'.'.implode(' = ~.',$value)); } } $join = implode('',$cond); } $data = preg_replace('#`([^`]+?)\.([^`]+?)`#', '$1.`$2`', $data); $data = preg_replace('#`(.+?) as (.*?)`#i','`$1` AS `$2`', $data); $data = preg_replace('#`([a-z0-9]+\(.*?\))`#i', '$1', $data); $where = preg_replace('#`([^`]+?)\.([^`]+?)`#', '$1.`$2`', $where); $order = preg_replace('#`([^`]+?)\.([^`]+?)`#', '$1.`$2`', $order); $join = preg_replace('#`([^`]+?)\.([^`]+?)`#', '$1.`$2`', $join); if(empty($where)) $where = ''; if(empty($order)) $order = ''; if(empty($join)) $join = ''; $sql = 'SELECT '.$data.' FROM '.$table.$join.(!empty($where) ? ' WHERE '.$where : '').(!empty($order) ? ' ORDER BY '.$order : ''); //exit($sql); try{ $STH = $DB->prepare($sql); $STH->execute(); $retVal = $STH->fetchAll(PDO::FETCH_ASSOC); if($debug===true) { $dump = print_r($STH, true).": ".print_r($retVal, true); print($dump.'
'); file_put_contents("query_debug.txt", $dump."\r\n", FILE_APPEND); } return $retVal; } catch(PDOException $err) { print_r($STH); print('
'); print_r($err); die(); } } function getOptions($data, $debug=false) { global $DB; $STH = ""; $sql = 'SELECT * FROM options WHERE name IN (\''.implode('\',\'',$data).'\');'; try { $STH = $DB->prepare($sql); $STH->execute($data); if($debug===true) { $dump = print_r($STH); print($dump); print('
'); file_put_contents("query_debug.txt", $dump."\r\n", FILE_APPEND); } return $STH->fetchAll(PDO::FETCH_ASSOC); } catch(Exception $err) { print_r($STH); print('
'); print_r($err); } }