3 // MySQL database class
5 // For debugging, insert 'dbg(x);' anywhere in the program flow.
6 // x = 1: display db success/failure following content
7 // x = 2: display full queries following content
8 // x = 3: display full queries using echo; which will mess up display
9 // really bad but will return output in stubborn cases.
11 if(! class_exists('dba')) {
17 function __construct($server,$user,$pass,$db,$install = false) {
18 $this->db = @new mysqli($server,$user,$pass,$db);
19 if((mysqli_connect_errno()) && (! install))
23 public function getdb() {
27 public function q($sql) {
33 $result = @$this->db->query($sql);
40 $debug_text .= $this->db->error . EOL;
44 elseif($result === true)
47 $mesg = $result->num_rows.' results' . EOL;
49 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg . EOL;
51 switch($this->debug) {
61 if($result === false) {
62 logger('dba: ' . printable($sql) . ' returned false.');
63 if(file_exists('dbfail.out'))
64 file_put_contents('dbfail.out', printable($sql) . ' returned false' . "\n", FILE_APPEND);
68 if(($result === true) || ($result === false))
72 if($result->num_rows) {
73 while($x = $result->fetch_array(MYSQL_ASSOC))
75 $result->free_result();
79 $debug_text .= printable(print_r($r, true). EOL);
80 elseif($this->debug == 3)
81 echo printable(print_r($r, true) . EOL) ;
86 public function dbg($dbg) {
90 public function escape($str) {
91 return @$this->db->real_escape_string($str);
94 function __destruct() {
99 if(! function_exists('printable')) {
100 function printable($s) {
101 $s = preg_replace("~([\x01-\x08\x0E-\x0F\x10-\x1F\x7F-\xFF])~",".", $s);
102 $s = str_replace("\x00",'.',$s);
103 if(x($_SERVER,'SERVER_NAME'))
104 $s = escape_tags($s);
108 // Procedural functions
109 if(! function_exists('dbg')) {
110 function dbg($state) {
115 if(! function_exists('dbesc')) {
116 function dbesc($str) {
118 return($db->escape($str));
122 // Function: q($sql,$args);
123 // Description: execute SQL query with printf style args.
124 // Example: $r = q("SELECT * FROM `%s` WHERE `uid` = %d",
127 if(! function_exists('q')) {
131 $args = func_get_args();
133 $ret = $db->q(vsprintf($sql,$args));
138 // Caller is responsible for ensuring that any integer arguments to
139 // dbesc_array are actually integers and not malformed strings containing
140 // SQL injection vectors. All integer array elements should be specifically
141 // cast to int to avoid trouble.
144 if(! function_exists('dbesc_array_cb')) {
145 function dbesc_array_cb(&$item, $key) {
147 $item = dbesc($item);
151 if(! function_exists('dbesc_array')) {
152 function dbesc_array(&$arr) {
153 if(is_array($arr) && count($arr)) {
154 array_walk($arr,'dbesc_array_cb');