]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/ezSQL/ez_sql_pdo.php
Add mysql, mysqli and PDO support
[Github/YOURLS.git] / includes / ezSQL / ez_sql_pdo.php
1 <?php
2
3         /**********************************************************************
4         *  Author: Justin Vincent (jv@jvmultimedia.com)
5         *  Web...: http://twitter.com/justinvincent
6         *  Name..: ezSQL_pdo
7         *  Desc..: SQLite component (part of ezSQL databse abstraction library)
8         *
9         */
10
11         /**********************************************************************
12         *  ezSQL error strings - SQLite
13         */
14
15         $ezsql_pdo_str = array
16         (
17                 1 => 'Require $dsn and $user and $password to create a connection'
18         );
19
20         /**********************************************************************
21         *  ezSQL Database specific class - SQLite
22         */
23
24         if ( ! class_exists ('PDO') ) die('<b>Fatal Error:</b> ezSQL_pdo requires PDO Lib to be compiled and or linked in to the PHP engine');
25         if ( ! class_exists ('ezSQLcore') ) die('<b>Fatal Error:</b> ezSQL_pdo requires ezSQLcore (ez_sql_core.php) to be included/loaded before it can be used');
26
27         class ezSQL_pdo extends ezSQLcore
28         {
29
30                 var $dsn;
31                 var $user;
32                 var $password;
33
34                 /**********************************************************************
35                 *  Constructor - allow the user to perform a qucik connect at the 
36                 *  same time as initialising the ezSQL_sqlite class
37                 */
38
39                 function ezSQL_pdo($dsn='', $user='', $password='', $ssl=array())
40                 {
41                         // Turn on track errors 
42                         ini_set('track_errors',1);
43                         
44                         if ( $dsn && $user && $password )
45                         {
46                                 $this->connect($dsn, $user, $password);
47                         }
48                 }
49
50                 /**********************************************************************
51                 *  Try to connect to SQLite database server
52                 */
53
54                 function connect($dsn='', $user='', $password='', $ssl=array())
55                 {
56                 
57                         global $ezsql_pdo_str; $return_val = false;
58                         
59                         // Must have a user and a password
60                         if ( ! $dsn || ! $user || ! $password )
61                         {
62                                 $this->register_error($ezsql_pdo_str[1].' in '.__FILE__.' on line '.__LINE__);
63                                 $this->show_errors ? trigger_error($ezsql_pdo_str[1],E_USER_WARNING) : null;
64                         }
65                         
66                         // Establish PDO connection
67                         try 
68                         {
69                                 if(!empty($ssl))
70                                 {
71                                         $this->dbh = new PDO($dsn, $user, $password, $ssl);
72                                 }
73                                 else
74                                 {
75                                         $this->dbh = new PDO($dsn, $user, $password);
76                                 }
77                                 
78                                 $return_val = true;
79                         } 
80                         catch (PDOException $e) 
81                         {
82                                 $this->register_error($e->getMessage());
83                                 $this->show_errors ? trigger_error($e->getMessage(),E_USER_WARNING) : null;
84                         }
85
86                         return $return_val;                     
87                 }
88
89                 /**********************************************************************
90                 *  In the case of SQLite quick_connect is not really needed
91                 *  because std. connect already does what quick connect does - 
92                 *  but for the sake of consistency it has been included
93                 */
94
95                 function quick_connect($dsn='', $user='', $password='', $ssl=array())
96                 {
97                         return $this->connect($dsn, $user, $password);
98                 }
99
100                 /**********************************************************************
101                 *  No real equivalent of mySQL select in SQLite 
102                 *  once again, function included for the sake of consistency
103                 */
104
105                 function select($dsn='', $user='', $password='', $ssl=array())
106                 {
107                         return $this->connect($dsn, $user, $password);
108                 }
109                 
110                 /**********************************************************************
111                 *  Format a SQLite string correctly for safe SQLite insert
112                 *  (no mater if magic quotes are on or not)
113                 */
114
115                 function escape($str)
116                 {
117                         switch (gettype($str))
118                         {
119                                 case 'string' : $str = addslashes(stripslashes($str));
120                                 break;
121                                 case 'boolean' : $str = ($str === FALSE) ? 0 : 1;
122                                 break;
123                                 default : $str = ($str === NULL) ? 'NULL' : $str;
124                                 break;
125                         }
126
127                         return $str;
128                 }
129
130                 /**********************************************************************
131                 *  Return SQLite specific system date syntax 
132                 *  i.e. Oracle: SYSDATE Mysql: NOW()
133                 */
134
135                 function sysdate()
136                 {
137                         return "datetime('now')";                       
138                 }
139
140                 /**********************************************************************
141                 *  Hooks into PDO error system and reports it to user
142                 */
143
144                 function catch_error()
145                 {
146                         $error_str = 'No error info';
147                                                 
148                         $err_array = $this->dbh->errorInfo();
149                         
150                         // Note: Ignoring error - bind or column index out of range
151                         if ( isset($err_array[1]) && $err_array[1] != 25)
152                         {
153                                 
154                                 $error_str = '';
155                                 foreach ( $err_array as $entry )
156                                 {
157                                         $error_str .= $entry . ', ';
158                                 }
159
160                                 $error_str = substr($error_str,0,-2);
161
162                                 $this->register_error($error_str);
163                                 $this->show_errors ? trigger_error($error_str.' '.$this->last_query,E_USER_WARNING) : null;
164                                 
165                                 return true;
166                         }
167
168                 }
169
170                 // ==================================================================
171                 //      Basic Query     - see docs for more detail
172
173                 function query($query)
174                 {
175
176                         // For reg expressions
177                         $query = str_replace("/[\n\r]/",'',trim($query)); 
178
179                         // initialise return
180                         $return_val = 0;
181
182                         // Flush cached values..
183                         $this->flush();
184
185                         // Log how the function was called
186                         $this->func_call = "\$db->query(\"$query\")";
187
188                         // Keep track of the last query for debug..
189                         $this->last_query = $query;
190
191                         $this->num_queries++;
192
193                         // Start timer
194                         $this->timer_start($this->num_queries);
195
196                         // Use core file cache function
197                         if ( $cache = $this->get_cache($query) )
198                         {
199
200                                 // Keep tack of how long all queries have taken
201                                 $this->timer_update_global($this->num_queries);
202
203                                 // Trace all queries
204                                 if ( $this->use_trace_log )
205                                 {
206                                         $this->trace_log[] = $this->debug(false);
207                                 }
208
209                                 return $cache;
210                         }
211
212                         // If there is no existing database connection then try to connect
213                         if ( ! isset($this->dbh) || ! $this->dbh )
214                         {
215                                 $this->connect($this->dsn, $this->user, $this->password);
216                         }
217
218                         // Query was an insert, delete, update, replace
219                         if ( preg_match("/^(insert|delete|update|replace|drop|create)\s+/i",$query) )
220                         {               
221
222                                 // Perform the query and log number of affected rows
223                                 $this->rows_affected = $this->dbh->exec($query);
224         
225                                 // If there is an error then take note of it..
226                                 if ( $this->catch_error() ) return false;
227
228                                 $is_insert = true;
229
230                                 // Take note of the insert_id
231                                 if ( preg_match("/^(insert|replace)\s+/i",$query) )
232                                 {
233                                         $this->insert_id = @$this->dbh->lastInsertId(); 
234                                 }
235
236                                 // Return number fo rows affected
237                                 $return_val = $this->rows_affected;
238         
239                         }
240                         // Query was an select
241                         else
242                         {
243
244                                 // Perform the query and log number of affected rows
245                                 $sth = $this->dbh->query($query);
246         
247                                 // If there is an error then take note of it..
248                                 if ( $this->catch_error() ) return false;
249
250                                 $is_insert = false;
251                                 
252                                 $col_count = $sth->columnCount();
253                                 
254                                 for ( $i=0 ; $i < $col_count ; $i++ )
255                                 {
256                                         $this->col_info[$i] = new stdClass();
257                                         
258                                         if ( $meta = $sth->getColumnMeta($i) )
259                                         {                                       
260                                                 $this->col_info[$i]->name =  $meta['name'];
261                                                 $this->col_info[$i]->type =  !empty($meta['native_type']) ? $meta['native_type'] : 'undefined';
262                                                 $this->col_info[$i]->max_length =  '';
263                                         }
264                                         else
265                                         {
266                                                 $this->col_info[$i]->name =  'undefined';
267                                                 $this->col_info[$i]->type =  'undefined';
268                                                 $this->col_info[$i]->max_length = '';
269                                         }
270                                 }
271
272                                 // Store Query Results
273                                 $num_rows=0;
274                                 while ( $row = @$sth->fetch(PDO::FETCH_ASSOC) )
275                                 {
276                                         // Store relults as an objects within main array
277                                         $this->last_result[$num_rows] = (object) $row;
278                                         $num_rows++;
279                                 }
280
281                                 // Log number of rows the query returned
282                                 $this->num_rows = $num_rows;
283
284                                 // Return number of rows selected
285                                 $return_val = $this->num_rows;
286
287                         }
288                         
289                         // disk caching of queries
290                         $this->store_cache($query,$is_insert);
291
292                         // If debug ALL queries
293                         $this->trace || $this->debug_all ? $this->debug() : null ;
294
295                         // Keep tack of how long all queries have taken
296                         $this->timer_update_global($this->num_queries);
297
298                         // Trace all queries
299                         if ( $this->use_trace_log )
300                         {
301                                 $this->trace_log[] = $this->debug(false);
302                         }
303                         
304                         return $return_val;
305
306                 }
307
308         }