1 |
rodolico |
1 |
<?php
|
|
|
2 |
|
13 |
rodolico |
3 |
/*
|
|
|
4 |
* Class DBQuery
|
|
|
5 |
*
|
16 |
rodolico |
6 |
* PHP Class as a wrapper around the mysqli class. Allows you to make
|
13 |
rodolico |
7 |
* the connection and run queries and/or DDL's if needed with the
|
16 |
rodolico |
8 |
* most common parameters (ie, not as flexible as mysqli itself).
|
13 |
rodolico |
9 |
* Enhancements include:
|
|
|
10 |
*
|
|
|
11 |
* Logs all queries with an optional username except select statements
|
|
|
12 |
* ie, anything that will change the system ( insert, delete, update,
|
|
|
13 |
* create, drop, alter, etc... ). Statement are logged with a date/time
|
|
|
14 |
* stamp, the user who performed the function, and the query executed
|
|
|
15 |
*
|
|
|
16 |
* Errors are simply trapped and the message is stored in the public
|
|
|
17 |
* member $error. Functions which find an error return boolean false
|
|
|
18 |
*
|
|
|
19 |
* Public Functions are:
|
|
|
20 |
* __construct -- creates connection
|
|
|
21 |
* doSQL -- executes an SQL query or DDL
|
|
|
22 |
* errors -- returns all errors not yet cleared
|
|
|
23 |
* can also directly access via public member errors
|
|
|
24 |
*
|
|
|
25 |
* public static function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' ) {
|
1 |
rodolico |
26 |
|
4 |
rodolico |
27 |
|
13 |
rodolico |
28 |
* Author: R. W. Rodolico (rodo@dailydata.net)
|
|
|
29 |
* Date: 2018-04-30
|
|
|
30 |
*
|
|
|
31 |
*/
|
|
|
32 |
|
|
|
33 |
class DBQuery extends mysqli {
|
|
|
34 |
|
|
|
35 |
/* everything is in the one $parameters array, which can then
|
|
|
36 |
* be set/saved/loaded as needed
|
|
|
37 |
*/
|
6 |
rodolico |
38 |
protected $parameters = array(
|
13 |
rodolico |
39 |
// query(s) to be run
|
|
|
40 |
'query' => '',
|
|
|
41 |
// additional clause to be added to where on a statement
|
|
|
42 |
'whereClause' => '',
|
|
|
43 |
// additional order by clause to be added
|
|
|
44 |
'orderBy' => '',
|
|
|
45 |
// the number of rows 1) affectd by an insert, update or delete or 2) returned by a select
|
|
|
46 |
'rowsAffected' => '',
|
|
|
47 |
// the value of the last row inserted
|
|
|
48 |
'lastInsertKey' => '',
|
|
|
49 |
// an array that contains the data retrieved by a query (select only)
|
29 |
rodolico |
50 |
'returnData' => array(),
|
13 |
rodolico |
51 |
// an array that contains the meta data from the query for each column
|
29 |
rodolico |
52 |
'columnMetaData' => array(),
|
13 |
rodolico |
53 |
// number of columns (fields) returned by query (select only)
|
|
|
54 |
'numfields' => 0,
|
|
|
55 |
// type of data returned, array of array, array of hash, or both
|
36 |
rodolico |
56 |
'fetchType' => MYSQLI_BOTH,
|
13 |
rodolico |
57 |
// human readable form of fetchType
|
36 |
rodolico |
58 |
'returnType' => 'both',
|
13 |
rodolico |
59 |
// array of any errors which occurred
|
|
|
60 |
'error' => array(),
|
|
|
61 |
// if set to a table name, all modifying queries are written to it
|
|
|
62 |
// must contain, at a minimum, columns whenrun timestamp, whoran varchar and query text
|
|
|
63 |
// can be created with $this->buildAuditTable
|
|
|
64 |
'auditTable' => '_activity_log'
|
|
|
65 |
);
|
|
|
66 |
|
37 |
rodolico |
67 |
public function __construct( $server, $username, $password, $database ) {
|
|
|
68 |
parent::__construct( $server, $username, $password, $database );
|
|
|
69 |
}
|
4 |
rodolico |
70 |
|
13 |
rodolico |
71 |
/*
|
|
|
72 |
* static function which simply parses out an error and returns
|
|
|
73 |
* a string suitable for printing. NOTE: it includes line returns
|
|
|
74 |
*/
|
|
|
75 |
public static function error2String( $error ) {
|
|
|
76 |
$return = array();
|
|
|
77 |
for ( $i = 0; $i < count( $error ); $i++ ) {
|
|
|
78 |
$return[] = implode( "\n", array( 'Error ' . $error[$i]['id'] . ' - ' . $error[$i]['message'], 'while executing query', $error[$i]['query'] ) );
|
6 |
rodolico |
79 |
}
|
13 |
rodolico |
80 |
return implode( "\n\n", $return ) . "\n";
|
|
|
81 |
} // error2String
|
6 |
rodolico |
82 |
|
13 |
rodolico |
83 |
// simply returns parameters for saving and reloading later
|
6 |
rodolico |
84 |
public function save() {
|
|
|
85 |
return $this->parameters;
|
|
|
86 |
} // function save
|
13 |
rodolico |
87 |
|
|
|
88 |
// loads parameters from $this->save(), or hand built
|
6 |
rodolico |
89 |
public function load( $parameters = array() ) {
|
|
|
90 |
$this->parameters = $parameters;
|
|
|
91 |
} // function load
|
|
|
92 |
|
13 |
rodolico |
93 |
// sets a key/value pair in $this->parameters
|
|
|
94 |
// returns $value
|
1 |
rodolico |
95 |
public function __set( $name, $value ) {
|
6 |
rodolico |
96 |
$this->parameters[$name] = $value;
|
4 |
rodolico |
97 |
return $value;
|
1 |
rodolico |
98 |
}
|
13 |
rodolico |
99 |
|
|
|
100 |
// gets the current value of $this->parameters[$name]
|
1 |
rodolico |
101 |
public function __get( $name ) {
|
6 |
rodolico |
102 |
return isset( $this->parameters[$name] ) ? $this->parameters[$name] : null;
|
1 |
rodolico |
103 |
}
|
13 |
rodolico |
104 |
|
|
|
105 |
// returns true if $parameters[$name] is set
|
1 |
rodolico |
106 |
public function __isset( $name ) {
|
6 |
rodolico |
107 |
return isset( $this->parameters[$name] );
|
1 |
rodolico |
108 |
}
|
13 |
rodolico |
109 |
|
|
|
110 |
|
|
|
111 |
/*
|
|
|
112 |
* function: buildAuditTable
|
|
|
113 |
* parameters:
|
|
|
114 |
* $tablename - name of table to be built
|
|
|
115 |
* $createStatement - SQL DDL to build the table
|
|
|
116 |
*
|
|
|
117 |
* If $tablename is set, will use that, otherwise will use
|
|
|
118 |
* $parameters[auditTable]. In either case, $parameters[auditTable]
|
|
|
119 |
* is set to the value of the table used
|
|
|
120 |
*
|
|
|
121 |
* if $createStatement is set, will be run WITHOUT MODIFICATION, and
|
|
|
122 |
* $parameters[auditTable] is not set to anything (unless $tablename
|
|
|
123 |
* is set)
|
|
|
124 |
*
|
|
|
125 |
* If $createStatement is not set, will use a default to build
|
|
|
126 |
* a table from $parameters[auditTable].
|
|
|
127 |
*
|
|
|
128 |
* Can definitely blow up if the table name is not set both places
|
|
|
129 |
* or if $createStatement is fubar
|
|
|
130 |
*/
|
|
|
131 |
|
|
|
132 |
public function buildAuditTable( $tablename = '', $createStatement = '' ) {
|
|
|
133 |
if ( $tablename ) // they sent us one, so set it
|
|
|
134 |
$this->parameters[ 'auditTable' ] = $tablename;
|
|
|
135 |
if ( ! $createStatement ) { // they did not set createStatement, so use our default
|
15 |
rodolico |
136 |
$auditTable = $this->parameters['auditTable'];
|
13 |
rodolico |
137 |
$createStatement = "
|
29 |
rodolico |
138 |
create table if not exists $auditTable (
|
13 |
rodolico |
139 |
_activity_log_id int unsigned not null auto_increment,
|
|
|
140 |
timestamp timestamp,
|
|
|
141 |
user varchar(64),
|
|
|
142 |
query text,
|
|
|
143 |
primary key(_activity_log_id)
|
|
|
144 |
) comment 'tracks queries which modify data'";
|
|
|
145 |
} // if
|
|
|
146 |
if ( parent::query( $createStatement ) === false ) {
|
|
|
147 |
// on error, die
|
|
|
148 |
print "Can not create audit table with query<br />\n$createStatement<br />\n";
|
|
|
149 |
die ( printf("Errormessage: %d - %s\n", $this->errno, $this->error ) );
|
|
|
150 |
} // if error, die
|
|
|
151 |
} // buildAuditTable
|
|
|
152 |
|
|
|
153 |
/*
|
|
|
154 |
* log queries to a table, file, or nothing
|
|
|
155 |
* log contains date/time, username and query
|
|
|
156 |
* to turn off logginging:
|
|
|
157 |
* unset( $parameters['auditTable'] )
|
|
|
158 |
*/
|
|
|
159 |
private function logIt( $username, $query, $recursion = false ) {
|
|
|
160 |
if ( ! isset( $this->parameters['auditTable'] ) )
|
|
|
161 |
return;
|
|
|
162 |
$username = $this->real_escape_string( $username );
|
|
|
163 |
$query = $this->real_escape_string( $query );
|
15 |
rodolico |
164 |
$logEntry = "insert into " . $this->parameters['auditTable'] . " (user, query) values ( '$username', '$query')";
|
13 |
rodolico |
165 |
//print "Loggging\n$logEntry\n";
|
|
|
166 |
if ( parent::query( $logEntry ) !== false ) { // good
|
|
|
167 |
return;
|
|
|
168 |
} else { // we had an error
|
|
|
169 |
if ( ! $recursion && $this->errno == 1146 ) { // table doesn't exist, so let's create it
|
15 |
rodolico |
170 |
$result = parent::query( "show tables like '" . $this->parameters['auditTable'] . "'" );
|
13 |
rodolico |
171 |
if ( $result->num_rows == 0 ) {
|
|
|
172 |
$this->buildAuditTable( );
|
|
|
173 |
return $this->logIt( $username, $query, true );
|
|
|
174 |
}
|
6 |
rodolico |
175 |
} else {
|
13 |
rodolico |
176 |
print "Trying to log transaction with query<br />\n$logEntry<br />\n";
|
|
|
177 |
die ( printf("Errormessage: %d - %s\n", $this->errno, $this->error ) );
|
|
|
178 |
} // if..else
|
1 |
rodolico |
179 |
} // if
|
13 |
rodolico |
180 |
} // function logIt
|
|
|
181 |
|
|
|
182 |
|
|
|
183 |
/*
|
|
|
184 |
* doSQL
|
|
|
185 |
* Parameters: $query - string or array of strings to be executed
|
|
|
186 |
* $parameters - hash used to pass additional parameters, to include
|
|
|
187 |
* $parameters['username'] = 'fred'; // username for logging
|
36 |
rodolico |
188 |
* $parameters['returnType'] = 'hash'; or array or both
|
13 |
rodolico |
189 |
*
|
|
|
190 |
* executes one or more queries
|
|
|
191 |
*
|
|
|
192 |
* If the query is one of select, show, describe or explain, it must
|
|
|
193 |
* be a single string. It will return the data results in a hash
|
|
|
194 |
* containing
|
|
|
195 |
* 'data' - an array of array/hash/both depending on what you asked for
|
|
|
196 |
* 'count' - number of results (ie, count(data)
|
|
|
197 |
* 'meta' - metadata for each column returned
|
|
|
198 |
* 'numfields' - number of columns in result (ie, count(meta))
|
|
|
199 |
* 'errors' - normally empty array of errors
|
|
|
200 |
*
|
|
|
201 |
* if the query modifies data (ie, NOT above), query may be an array
|
|
|
202 |
* which will be surrounded by a transaction and rolled back if
|
|
|
203 |
* anything causes an error.
|
|
|
204 |
*
|
|
|
205 |
* These will return a hash containing
|
|
|
206 |
* 'count' l- number of rows affected by last statement
|
|
|
207 |
* 'last_insert_id' - last insert id created by BLOCK of queries
|
|
|
208 |
* 'errors' - normally empty array of errors which occurred (caused a rollback)
|
|
|
209 |
*
|
|
|
210 |
*/
|
15 |
rodolico |
211 |
public function doSQL( $query = null, $parameters = array() ) {
|
13 |
rodolico |
212 |
$errors = array();
|
15 |
rodolico |
213 |
if ( isset( $query ) ) {
|
|
|
214 |
$this->parameters['query'] = $query;
|
|
|
215 |
}
|
13 |
rodolico |
216 |
// if it is a "selectstatement" it doesn't modify data
|
|
|
217 |
// if query is an array, assume it modifies something
|
|
|
218 |
// if it is a single statement, look for the regex
|
15 |
rodolico |
219 |
$selectStatement = is_array( $this->parameters['query'] ) ?
|
13 |
rodolico |
220 |
false :
|
29 |
rodolico |
221 |
( preg_match( '/^\s*(select)|(show)|(describe)|(explain)/xsi', $this->parameters['query'] ) === 1 );
|
13 |
rodolico |
222 |
|
|
|
223 |
// different actions based on whether it modifies data or not
|
|
|
224 |
if ( $selectStatement ) { // if a select, simply return the rows
|
|
|
225 |
// dataset is small enough, we just read it into memory all at one time.
|
|
|
226 |
// NOTE: fetch_all is nice, but tied to mysqlnd, which has reports of problems, so we do it the old way
|
15 |
rodolico |
227 |
if ( $sth = parent::query( $this->parameters['query'], MYSQLI_USE_RESULT ) ) {
|
13 |
rodolico |
228 |
if ( $sth === false ) {
|
|
|
229 |
$errors[] = array( 'id' => $this->errno, 'message' => $this->error );
|
|
|
230 |
} else {
|
|
|
231 |
$this->parameters['columnMetaData'] = $sth->fetch_fields(); // get metadata
|
|
|
232 |
$this->parameters['returnData'] = array(); // we'll put all the results in an array
|
|
|
233 |
// $fetchtype returns either an array of array, array of hash, or both. Default is array of hash
|
36 |
rodolico |
234 |
if ( isset( $this->parameters['returnType'] ) ) {
|
|
|
235 |
$this->parameters[ 'fetchType' ] = $this->parameters['returnType'] == 'array' ? MYSQLI_NUM : (
|
|
|
236 |
( $this->parameters['returnType'] == 'both' ) ? MYSQLI_BOTH : MYSQLI_ASSOC
|
13 |
rodolico |
237 |
);
|
36 |
rodolico |
238 |
} else { // default is both (hash and numeric)
|
|
|
239 |
$this->parameters[ 'fetchType' ] = MYSQLI_BOTH;
|
|
|
240 |
$this->parameters['returnType'] = 'both';
|
13 |
rodolico |
241 |
}
|
|
|
242 |
// slurp all the stuff in
|
|
|
243 |
while ( $values = $sth->fetch_array( $this->parameters[ 'fetchType' ] ) ) {
|
|
|
244 |
$this->parameters[ 'returnData' ][] = $values;
|
|
|
245 |
}
|
|
|
246 |
$sth->free(); // cleanup memory, don't need two copies
|
|
|
247 |
} // if we had no errors
|
1 |
rodolico |
248 |
}
|
13 |
rodolico |
249 |
$this->parameters[ 'rowsAffected' ] = count( $this->parameters[ 'returnData' ] );
|
|
|
250 |
$this->parameters[ 'numfields' ] = count( $this->parameters['columnMetaData'] );
|
|
|
251 |
$this->parameters[ 'lastInsertKey' ] = 0;
|
|
|
252 |
$this->parameters[ 'error' ] = $errors;
|
|
|
253 |
} else {
|
|
|
254 |
if ( ! is_array( $this->parameters['query'] ) ) { // not an array, so make it one
|
|
|
255 |
$temp = $this->parameters['query'];
|
|
|
256 |
$this->parameters['query'] = array( $temp );
|
1 |
rodolico |
257 |
}
|
13 |
rodolico |
258 |
// do it in a transaction so we can back out on failure
|
|
|
259 |
$this->autocommit(false);
|
|
|
260 |
$allOk = true;
|
|
|
261 |
for ( $i = 0; $i < count( $this->parameters['query'] ); $i++ ) {
|
15 |
rodolico |
262 |
// debugging
|
|
|
263 |
//print "$i\t" . $this->parameters['query'][$i] ."\n"; continue;
|
|
|
264 |
// debugging
|
13 |
rodolico |
265 |
$this->logIt( isset( $parameters['username'] ) ? $parameters['username'] : 'unknown', $this->parameters['query'][$i] );
|
|
|
266 |
if ( parent::query( $this->parameters['query'][$i] ) === false ) { // we had an erorr
|
|
|
267 |
// record it
|
|
|
268 |
$errors[] = array( 'id' => $this->errno, 'message' => $this->error, 'query' => $this->parameters['query'][$i] );
|
|
|
269 |
$allOk = false;
|
|
|
270 |
// and bail
|
|
|
271 |
break;
|
|
|
272 |
}
|
|
|
273 |
}
|
|
|
274 |
// if we made it through ok, commit, otherwise rollback
|
|
|
275 |
$allOk ? $this->commit() : $this->rollback();
|
|
|
276 |
// reset autocommit to true
|
|
|
277 |
$this->autocommit(true);
|
|
|
278 |
$this->parameters['query'] = $query;
|
|
|
279 |
$this->parameters[ 'rowsAffected' ] = $this->affected_rows;
|
|
|
280 |
$this->parameters[ 'lastInsertKey' ] = $this->insert_id;
|
|
|
281 |
$this->parameters[ 'error' ] = $errors;
|
|
|
282 |
} // if select .. else
|
|
|
283 |
return $this->parameters;
|
|
|
284 |
} // function doSQL
|
17 |
rodolico |
285 |
|
|
|
286 |
public function run () {
|
|
|
287 |
return $this->doSQL( );
|
|
|
288 |
}
|
34 |
rodolico |
289 |
|
|
|
290 |
/**
|
|
|
291 |
* returns an array of the first column for each row returned from query
|
|
|
292 |
*
|
|
|
293 |
* The query is run, then for each row returns, the first column
|
|
|
294 |
* is added to $return (an array). $return is then returned.
|
|
|
295 |
*
|
|
|
296 |
* Used to do things like get an array of keyfields, or something
|
|
|
297 |
* else.
|
|
|
298 |
*
|
|
|
299 |
* @param string $query Query to run
|
|
|
300 |
* @returns string[] Array of values
|
|
|
301 |
*/
|
|
|
302 |
public function columnToArray( $query ) {
|
|
|
303 |
$return = array();
|
|
|
304 |
$result = $this->doSQL( $query );
|
|
|
305 |
foreach ( $result['returnData'] as $row ) {
|
|
|
306 |
$return[] = $row['id'];
|
|
|
307 |
}
|
|
|
308 |
return $return;
|
|
|
309 |
}
|
1 |
rodolico |
310 |
|
|
|
311 |
/*
|
|
|
312 |
* function will return one and only one row, NOT as an array of array
|
|
|
313 |
* but as a single row array
|
|
|
314 |
* if more than one row is returned by query, error is set and function
|
|
|
315 |
* returns false.
|
|
|
316 |
* Otherwise, function returns true
|
|
|
317 |
*/
|
|
|
318 |
public function getOneRow( $sql = null ) {
|
|
|
319 |
if ( isset( $sql ) )
|
6 |
rodolico |
320 |
$this->parameters[ 'query' ] = $sql;
|
36 |
rodolico |
321 |
$save = $this->parameters[ 'returnType' ];
|
|
|
322 |
//print "<pre>" . print_r( $this->parameters['query'], true) . '</pre>';
|
1 |
rodolico |
323 |
$useAssociativeArray = true;
|
|
|
324 |
$this->run();
|
|
|
325 |
$useAssociativeArray = $save;
|
6 |
rodolico |
326 |
if ( $this->parameters[ 'rowsAffected' ] == 1 ) {
|
|
|
327 |
$this->parameters[ 'returnData' ] = $this->parameters[ 'returnData' ][0];
|
35 |
rodolico |
328 |
return $this->parameters[ 'returnData' ];
|
37 |
rodolico |
329 |
} else {
|
6 |
rodolico |
330 |
$this->parameters['error'] = "$this->parameters[query] did not return a unique row in getOneRow";
|
37 |
rodolico |
331 |
print_r( $this->parameters['query'] ); die;
|
|
|
332 |
}
|
1 |
rodolico |
333 |
return false;
|
|
|
334 |
} // getOneRow
|
|
|
335 |
|
|
|
336 |
|
|
|
337 |
// function returns the first column of the first row of data returned from query
|
|
|
338 |
// or null no value returned
|
6 |
rodolico |
339 |
public function getOneDBValue( $sql = null ) {
|
34 |
rodolico |
340 |
//print '<pre>' . $sql . '</pre>';
|
1 |
rodolico |
341 |
if ( isset( $sql ) )
|
6 |
rodolico |
342 |
$this->parameters[ 'query' ] = $sql;
|
36 |
rodolico |
343 |
$save = $this->parameters['returnType'];
|
|
|
344 |
$this->parameters['returnType'] = 'array';
|
1 |
rodolico |
345 |
$this->run();
|
36 |
rodolico |
346 |
$this->parameters['returnType'] = $save;
|
|
|
347 |
//print "<pre>" . print_r($this->parameters,true ) . "</pre>";
|
6 |
rodolico |
348 |
return $this->parameters[ 'rowsAffected' ] ? $this->parameters[ 'returnData' ][0][0] : null;
|
1 |
rodolico |
349 |
}
|
6 |
rodolico |
350 |
|
4 |
rodolico |
351 |
/*
|
|
|
352 |
* function will attempt to make a constant ($value) safe for SQL depending on the type.
|
|
|
353 |
*
|
|
|
354 |
* if $value is empty, $default is returned, as will happen if any of the
|
|
|
355 |
* conversions (date, datetime, etc...) fail.
|
|
|
356 |
*
|
|
|
357 |
* First, it will pass it through get_magic_quotes_gpc,
|
|
|
358 |
* then will run through mysql_real_escape_string
|
|
|
359 |
*
|
|
|
360 |
* For strings, will encapsulate in quotes
|
|
|
361 |
* Dates will attempt a conversion, then change to YYYY-MM-DD and encapsulate in quotes
|
|
|
362 |
* DateTime will perform the same, but change to YYYY-MM-DD HH:MM:SS
|
|
|
363 |
* Integer and Floats are passed through builtins intval and floatval
|
|
|
364 |
* Boolean only checks the first character, a '0', 'f' and 'n' denoting false
|
|
|
365 |
* all else denoting true. The result is converted based on the variable
|
|
|
366 |
* $falsetrue, with the first char denoting false and the second denoting true
|
|
|
367 |
*/
|
|
|
368 |
public static function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' ) {
|
|
|
369 |
if (strlen($value) == 0) // simply set any empty values to null
|
|
|
370 |
return $default;
|
|
|
371 |
// print "Processing $value as $type with default $default<br>\n";
|
|
|
372 |
switch ( strtolower( $type ) ) {
|
|
|
373 |
case 'string' :
|
|
|
374 |
case 's' :
|
|
|
375 |
if ( get_magic_quotes_gpc() )
|
|
|
376 |
$value = stripslashes($value);
|
13 |
rodolico |
377 |
$value = $this->real_escape_string( $value );
|
4 |
rodolico |
378 |
$value = strlen( $value ) > 0 ? "'$value'" : $default;
|
|
|
379 |
break;
|
|
|
380 |
case 'date' :
|
|
|
381 |
case 'd' :
|
|
|
382 |
if ( $value != 'null' ) {
|
|
|
383 |
$result = strtotime( $value );
|
|
|
384 |
$value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d', $result) . "'";
|
|
|
385 |
}
|
|
|
386 |
break;
|
|
|
387 |
case 'datetime':
|
|
|
388 |
case 'timestamp':
|
|
|
389 |
case 'dt':
|
|
|
390 |
if ( $value != 'null' ) {
|
|
|
391 |
$result = strtotime( $value );
|
|
|
392 |
$value = ( $result === false ) ? $default : "'" . Date( 'Y-m-d H:i:s', $result) . "'";
|
|
|
393 |
}
|
|
|
394 |
break;
|
|
|
395 |
case 'integer':
|
|
|
396 |
case 'i' :
|
|
|
397 |
$value = intval( $value );
|
|
|
398 |
break;
|
|
|
399 |
case 'float':
|
|
|
400 |
case 'f' :
|
|
|
401 |
$value = floatval( $value );
|
|
|
402 |
break;
|
|
|
403 |
case 'bool':
|
|
|
404 |
case 'boolean':
|
|
|
405 |
case 'b' : // note, because of the way strpos works, you can not
|
|
|
406 |
// simply set $value based on the output; you MUST do
|
|
|
407 |
// as below; specifically check for false, then set the result
|
|
|
408 |
$value = strpos( '0fn', strtolower(substr( $value, 0, 1 )) ) === false ? 0 : 1;
|
|
|
409 |
$value = substr( $falsetrue, $value, 0, 1 );
|
|
|
410 |
break;
|
|
|
411 |
} // switch
|
|
|
412 |
return $value;
|
|
|
413 |
}
|
1 |
rodolico |
414 |
|
29 |
rodolico |
415 |
/*
|
|
|
416 |
'[^']*(?!\\)'(*SKIP)(*F) # Make sure we're not matching inside of quotes
|
|
|
417 |
|(?m-s:\s*(?:\-{2}|\#)[^\n]*$) # Single line comment
|
|
|
418 |
|(?:
|
|
|
419 |
\/\*.*?\*\/ # Multi-line comment
|
|
|
420 |
(?(?=(?m-s:\h+$)) # Get trailing whitespace if any exists and only if it's the rest of the line
|
|
|
421 |
\h+
|
|
|
422 |
)
|
|
|
423 |
)
|
|
|
424 |
*/
|
|
|
425 |
/**
|
|
|
426 |
* Functions strips SQL queries from a file. Above is a commented copy of the regex used
|
|
|
427 |
*
|
|
|
428 |
* @param string $query An arbitrary sized SQL script
|
|
|
429 |
* @returns string $query, with all SQL comments removed
|
|
|
430 |
*/
|
4 |
rodolico |
431 |
|
29 |
rodolico |
432 |
public function strip_sqlcomment ($query = '') {
|
|
|
433 |
$regex = '\'[^\']*(?!\\\)\'(*SKIP)(*F)|(?m-s:\\s*(?:\\-{2}|\\#)[^\\n]*$)|(?:\\/\\*.*?\\*\\/(?(?=(?m-s:\h+$))\\h+))';
|
|
|
434 |
//print "<pre>$regex</pre>" ; die;
|
|
|
435 |
return (($query == '') ? '' : preg_replace( "/$regex/xs", '', $query ));
|
|
|
436 |
}
|
|
|
437 |
|
|
|
438 |
/**
|
|
|
439 |
* runs an SQL script with multiple statements in it
|
|
|
440 |
*
|
37 |
rodolico |
441 |
* If $sql is an array, it is assumed each row is a separate query
|
|
|
442 |
*
|
|
|
443 |
* If $sql is a string, will separate it into different lines and
|
|
|
444 |
* execute them
|
|
|
445 |
*
|
29 |
rodolico |
446 |
* NOTE: it does this by breaking it based on the semicolon, so
|
|
|
447 |
* in some weird situations, it will break at the wrong place.
|
|
|
448 |
*
|
|
|
449 |
*/
|
|
|
450 |
public function runSQLScript( $sql ) {
|
37 |
rodolico |
451 |
if ( is_array( $sql ) ) {
|
|
|
452 |
$queries = $sql;
|
|
|
453 |
} else {
|
|
|
454 |
$sql = $this->strip_sqlcomment( $sql );
|
|
|
455 |
$queries = explode( ";", $sql );
|
|
|
456 |
}
|
29 |
rodolico |
457 |
//print "<pre>" . print_r( $queries, true ) . '</pre>'; die;
|
|
|
458 |
foreach ( $queries as $query ) {
|
|
|
459 |
$this->doSQL( trim( implode( ' ', explode("\n",$query ) ) ) );
|
|
|
460 |
}
|
37 |
rodolico |
461 |
} // runSQLScript
|
|
|
462 |
|
|
|
463 |
/**
|
|
|
464 |
* Overrides real_escape_string to change behaviour slightly
|
|
|
465 |
*
|
|
|
466 |
* Will check if string is pure numeric and, if it is, will return
|
|
|
467 |
* as it is. Otherwise, will call real_escape_string, then wrap
|
|
|
468 |
* result in single quotes
|
|
|
469 |
*/
|
|
|
470 |
public function my_escape_string( $string, $additionalEscapes = array() ) {
|
|
|
471 |
if ( is_numeric( $string ) )
|
|
|
472 |
return $string;
|
|
|
473 |
$string = $this->real_escape_string( $string );
|
|
|
474 |
if ( count( $additionalEscapes ) )
|
|
|
475 |
$string = addcslashes( $string, implode( '', $additionalEscapes ) );
|
|
|
476 |
return "'$string'";
|
|
|
477 |
}
|
|
|
478 |
|
|
|
479 |
/**
|
|
|
480 |
* Builds a query of form update $tablename set $fields where $where
|
|
|
481 |
*
|
|
|
482 |
* Creates a query that will update table $tablename. It assumes
|
|
|
483 |
* $fields is an array where the indexes are fieldnames and the values
|
|
|
484 |
* are the new values for the field. Will escape the values.
|
|
|
485 |
*
|
|
|
486 |
* Appends $where, again where index is a field name
|
|
|
487 |
*/
|
|
|
488 |
public function updateQuery( $tablename, $where, $fields ) {
|
|
|
489 |
/*
|
|
|
490 |
print "<pre>updateQuery\n\ntable\n$tablename\n</pre>";
|
|
|
491 |
print "<pre>\nwhere\n" . print_r( $where, true ) . "\n</pre>";
|
|
|
492 |
print "<pre>fields\n" . print_r( $fields, true ) . "\n</pre>"; die;
|
|
|
493 |
*/
|
|
|
494 |
$sql = '';
|
|
|
495 |
$updateFields = array();
|
|
|
496 |
foreach ( $fields as $fieldname => $value ) {
|
|
|
497 |
$updateFields[] = sprintf( "%s = %s", $fieldname, $this->my_escape_string( $value ) );
|
|
|
498 |
}
|
|
|
499 |
$sql = "update $tablename set " . implode( ", ", $updateFields );
|
|
|
500 |
$updateFields = array();
|
|
|
501 |
foreach ( $where as $fieldname => $value ) {
|
|
|
502 |
$updateFields[] = sprintf( "%s = %s", $fieldname, $this->my_escape_string( $value ) );
|
|
|
503 |
}
|
|
|
504 |
if ( count( $updateFields ) ) {
|
|
|
505 |
$sql .= ' where ' . implode( ' and ', $updateFields );
|
|
|
506 |
}
|
|
|
507 |
return $sql;
|
|
|
508 |
}
|
|
|
509 |
|
|
|
510 |
/**
|
|
|
511 |
* Creates an insert query from $fields
|
|
|
512 |
*
|
|
|
513 |
*/
|
|
|
514 |
public function insertQuery( $tablename, $fields ) {
|
|
|
515 |
print "<pre>insertQuery\n\ntable\n$tablename\n</pre>";
|
|
|
516 |
print "<pre>fields\n" . print_r( $fields, true ) . "\n</pre>"; die;
|
|
|
517 |
$query = "insert into $tablename (" . implode( ',',array_keys($fields) );
|
|
|
518 |
$query .= " values (" . implode( ',', array_map( array($this, 'real_escape_string'), array_values( $fields ) ) );
|
|
|
519 |
return "$query)";
|
|
|
520 |
} // insertQuery
|
|
|
521 |
|
29 |
rodolico |
522 |
|
1 |
rodolico |
523 |
} // class DBQuery
|
|
|
524 |
|
17 |
rodolico |
525 |
/*
|
|
|
526 |
* $db = new DBQuery( '127.0.0.1', 'camp', 'camp', 'camp' );
|
13 |
rodolico |
527 |
|
|
|
528 |
if ($db->connect_error) {
|
|
|
529 |
die('Connect Error (' . $db->connect_errno . ') ' . $db->connect_error);
|
|
|
530 |
}
|
|
|
531 |
$result = $db->doSQL(
|
|
|
532 |
array(
|
|
|
533 |
'drop table if exists temp',
|
|
|
534 |
'create table temp ( col1 int unsigned )',
|
|
|
535 |
"insert into temp values ('mike')"
|
|
|
536 |
)
|
|
|
537 |
);
|
15 |
rodolico |
538 |
if ( $result['error'] ) {
|
13 |
rodolico |
539 |
print_r ( $result );
|
15 |
rodolico |
540 |
die ( DBQuery::error2String( $result['error'] ) );
|
13 |
rodolico |
541 |
} else {
|
|
|
542 |
print "running select\n";
|
|
|
543 |
$result = $db->doSQL( 'select * from temp' );
|
|
|
544 |
print_r( $result );
|
|
|
545 |
}
|
|
|
546 |
// $return = $db->doSQL( "select device.device_id 'id',device.name 'name', device_type.name 'type' from device join device_type using (device_type_id) where device.removed_date is null and device_type.show_as_system = 'Y'" );
|
|
|
547 |
// print_r( $return );
|
|
|
548 |
// print_r( $db );
|
17 |
rodolico |
549 |
*/
|
1 |
rodolico |
550 |
?>
|
13 |
rodolico |
551 |
|
|
|
552 |
|
|
|
553 |
|
|
|
554 |
|
|
|
555 |
|
|
|
556 |
|
|
|
557 |
|
|
|
558 |
|
|
|
559 |
|
|
|
560 |
|