7 * For debugging, insert 'dbg(1);' anywhere in the program flow.
8 * dbg(0); will turn it off. Logging is performed at LOGGER_DATA level.
9 * When logging, all binary info is converted to text and html entities are escaped so that
10 * the debugging stream is safe to view within both terminals and web pages.
14 if(! class_exists('dba')) {
20 function __construct($server,$user,$pass,$db,$install = false) {
21 $this->db = @new mysqli($server,$user,$pass,$db);
22 if((mysqli_connect_errno()) && (! $install))
26 public function getdb() {
30 public function q($sql) {
36 $result = @$this->db->query($sql);
43 logger('dba: ' . $this->db->error);
47 elseif($result === true)
50 $mesg = $result->num_rows.' results' . EOL;
52 $str = 'SQL = ' . printable($sql) . EOL . 'SQL returned ' . $mesg . EOL;
54 logger('dba: ' . $str );
59 * If dbfail.out exists, we will write any failed calls directly to it,
60 * regardless of any logging that may or may nor be in effect.
61 * These usually indicate SQL syntax errors that need to be resolved.
64 if($result === false) {
65 logger('dba: ' . printable($sql) . ' returned false.');
66 if(file_exists('dbfail.out'))
67 file_put_contents('dbfail.out', printable($sql) . ' returned false' . "\n", FILE_APPEND);
71 if(($result === true) || ($result === false))
75 if($result->num_rows) {
76 while($x = $result->fetch_array(MYSQL_ASSOC))
78 $result->free_result();
82 logger('dba: ' . printable(print_r($r, true)), LOGGER_DATA);
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));
137 // raw db query, no arguments
139 if(! function_exists('dbq')) {
148 // Caller is responsible for ensuring that any integer arguments to
149 // dbesc_array are actually integers and not malformed strings containing
150 // SQL injection vectors. All integer array elements should be specifically
151 // cast to int to avoid trouble.
154 if(! function_exists('dbesc_array_cb')) {
155 function dbesc_array_cb(&$item, $key) {
157 $item = dbesc($item);
161 if(! function_exists('dbesc_array')) {
162 function dbesc_array(&$arr) {
163 if(is_array($arr) && count($arr)) {
164 array_walk($arr,'dbesc_array_cb');