Subversion Repositories phpLibraryV2

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16 rodolico 1
<html>
2
   <body>
3
      <h1>DBQuery</h1>
4
      <p>
5
         The DBQuery class extends mysqli, so it inherits all of those functions. It can be used as a drop in replacement for mysqli with a few enhancements
6
      </p>
7
      <ul>
8
         <li>
9
            when using class function <i>doSQL</i>
10
            <ul>
11
               <li>
12
                  Accepts an array of queries to be executed
13
               </li>
14
               <li>
15
                  queries which modify data can be logged to a separate table in the database.
16
               </li>
17
               <li>
18
                  Error trapping done more conveniently, with lists of errors returned as part of the return value
19
               </li>
20
               <li>
21
                  queries which modify data are wrapped in a commit/rollback block, so any failure in any query results in the database being in the form it was before the block was executed
22
               </li>
23
               <li>
24
                  returns a hash containing all rows from a select, a count of the number of rows returned, any errors and meta data on the columns returned
25
               </li>
26
               </li>
27
                  on data modifying queries, returns number of rows affected, last_insert_id and errors
28
               </li>
29
            </ul>
30
         </li>
31
         <li>
32
            Additional convenience functions getOneRow and getOneDBValue
33
         </li>
34
         <li>
35
            Enhanced real_escape_string (function makeSafeSQLConstant)
36
            <ul>
37
               <li>
38
                  correctly delimits fields based on data type (default string)
39
               </li>
40
               <li>
41
                  interprets strings which are date, date/time, integer, float and boolean values
42
               </li>
43
            </ul>
44
         </li>
45
      </ul>
46
      <h2>public function doSQL( $query, $parameters )</h2>
47
      <ul>
48
         <li>
49
            $query<br />
50
            string containing a single <b>select</b>, <b>show</b>, <b>describe</b> or <b>explain</b> statement, or a single string/array of strings containing insert, delete, update or DDL statements.
51
         </li>
52
         <li>
53
            $parameters<br />
54
            hash of key/value pairs which is merged into class member $this->parameters. Convenient way to modify the way a query is executed. Also used to pass 'username' for audit function
55
         </li>
56
      </ul>
57
      <h3>Non Data Modifying queries</h3>
58
      <p>
59
         doSQL runs one query. A single string starting with one of the keywords <b>select</b>, <b>show</b>, <b>describe</b> or <b>explain</b> is run as is, with results stored in the $parameters hash which is returned by the function. Hash key/value pairs are as follows:
60
      </p>
61
      <ul>
62
         <li>
63
            'returnData'<br />
64
            Array (one row per return row from query). Each row contains either
65
            <ul>
66
               <li>
67
                  associative array, where key is field name and value is the value returned by the query
68
               </li>
69
               <li>
70
                  indexed array, where $parameters[0][0] is the first column of the first row returned
71
               </li>
72
               <li>
73
                  mixed array, each column is duplicated, combining associative and indexed
74
               </li>
75
            </ul>
76
         </li>
77
         <li>
78
            'columnMetaData'<br />
79
            metadata for each column returned by the query. See mysqli documentation for structure
80
         </li>
81
         <li>
82
            'returntype'<br />
83
            'fetchType'<br />
84
            type of result requested. 'returntype' is the human readable <i>associative</i>, <i>array</i> or <i>both</i>, and 'fetchType' is the actual mysqli constant associated with it. Default is 'associative' and MYSQLI_ASSOC
85
         </li>
86
         <li>
87
            'rowsAffected'<br />
88
            number of rows returned by query
89
         </li>
90
         <li>
91
            'numfields'<br />
92
            number of columns in results
93
         </li>
94
         <li>
95
            'error'<br />
96
            (possibly empty) indexed array of errors encountered.
97
         </li>
98
      </ul>
99
      <p>
100
         Following code illustrates how to use doSQL to run a simple query.
101
      </p>
102
      <pre>
103
            $db = new DBQuery( '127.0.0.1', 'camp', 'camp', 'camp' );
104
            if ($db->connect_error) {
105
                die('Connect Error (' . $db->connect_errno . ') '  . $db->connect_error);
106
            }
107
            $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'" );
108
            if ( $return['error'] ) {
109
               die ( DBQuery::error2String( $result['error'] ) );
110
            } else {
111
               for ( $i = 0; $i < $result['rowsAffected']; $i++ ) {
112
                  foreach ( $result['returnData'][$i] as $columnName => $value ) {
113
                     print "Row $i, Column $columnName == $value\n";
114
                  }
115
               }
116
            }
117
      </pre>
118
      <h3>Data Modifying queries</h3>
119
      <p>
120
         If the query is an array, or if it does <b>not</b> start with one of <b>select</b>, <b>show</b>, <b>describe</b> or <b>explain</b>, it is treated as a group of statements which will modify data. At this point, the query is treated differently.
121
      </p>
122
      <ul>
123
         <li>
124
            if it is a single string, it is converted to an array with one value
125
         </li>
126
         <li>
127
            mysqli::autocommit is turned off
128
         </li>
129
         <li>
130
            For each query in the array
131
            <ul>
132
               <li>
133
                  the function logIt is called, which records the query being executed
134
               </li>
135
               <li>
136
                  Query is executed
137
               </li>
138
               <li>
139
                  If an error occurs, no more statements are executed, the error array is updated with the mysql error
140
               </li>
141
            </ul>
142
         </li>
143
         <li>
144
            If no errors occured, a commit is executed. Otherwise, rollback is called
145
         </li>
146
      </ul>
147
      <p>
148
         When complete, the results are stored in the parameters also.
149
      </p>
150
      <ul>
151
         <li>
152
            'query'<br />
153
            contains the array of queries which were suposed to be executed
154
         </li>
155
         <li>
156
            'rowsAffected'<br />
157
            contains the number of rows modified by the <b>last</b> query executed
158
         </li>
159
         <li>
160
            'lastInsertKey'<br />
161
            contains the last used auto-increment value
162
         </li>
163
         <li>
164
            'error'<br />
165
            contains a (possibly empty) array of errors encountered
166
         </li>
167
      </ul>
168
      <p>
169
         Following code illustrates how to use doSQL to create a table and populate it
170
      </p>
171
      <pre>
172
         $db = new DBQuery( '127.0.0.1', 'camp', 'camp', 'camp' );
173
 
174
         if ($db->connect_error) {
175
             die('Connect Error (' . $db->connect_errno . ') '  . $db->connect_error);
176
         }
177
         $result = $db->doSQL(
178
                     array(
179
                           'drop table if exists temp',
180
                           'create table temp ( col1 int unsigned )',
181
                           "insert into temp values ('mike')"
182
                           )
183
               );
184
         if ( $result['error'] ) {
185
            print_r ( $result );
186
            die ( DBQuery::error2String( $result['error'] ) );
187
         }         
188
      </pre>
189
      <h2>private function logIt( $username, $query, $recursion = false )</h2>
190
      <p>
191
         this function stores all queries which modify data. The first two parameters are the user who is logged in, and the query being executed. The third parameter, $recursion, is only used internally do detect the function calling itself.
192
      </p>
193
      <p>
194
         logIt populates the table defined in $this->parameters['auditTable'] which defined as <b>_activity_log</b> by default. If the table does not exist, it is created with the following SQL.
195
      </p>
196
      <pre>
197
         create table _activity_log (
198
                  _activity_log_id int unsigned not null auto_increment,
199
                  timestamp  timestamp,
200
                  user       varchar(64),
201
                  query      text,
202
                  primary key(_activity_log_id)
203
               ) comment 'tracks queries which modify data         
204
      </pre>
205
      <p>
206
         The name of the table, and its structure can be overridden by directly calling <i>public function buildAuditTable( $tablename = '', $createStatement = '')</i>. If $tablename or $createStatement is not passed in, the defaults are used. The audit table <b>must</b> have the fields in question, however.
207
      </p>
208
      <h3>Update Statements</h3>
209
      <p>
210
         queries which begin with the keyword <b>update</b> are treated slightly different. The query is parsed for the table name and the where clause, and a new query is created which retrieves the values in the table before the update command is executed. All rows returned are then stored in the query column of the audit table before the command is executed. <b>Note: </b> this function only works for single table updates with clearly defined where clauses, ie update <i>tablename</i> set column=value, set column = value where <i>condition</i> [order by] ... [limit] ...
211
      </p>
212
      <h2>public static function makeSafeSQLConstant ( $value, $type='S', $default='null', $falsetrue='10' )</h2>
213
      <p>
214
         This is an extension of mysqli::real_escape_string which is aware of the data type you are expecting to pass in. The default is string, in which case it simply strips slashes, does the standard real_escape_string, and encloses the result in single quotes.
215
      </p>
216
      <p>
217
         In all cases, if $value is empty, returns keyword <i>null</i>. This can be overridden by setting the $default parameter (warning, you are responsible for delimiting and escaping this)
218
      </p>
219
      <p>
220
         If a data type other than string is set, the following actions are taken
221
      </p>
222
      <ul>
223
         <li>
224
            $type == 'date' or 'd'<br />
225
            attempts to convert the string to a date using strtotime, and returns it in the format YYYY-MM-DD enclosed in single quotes. Any time portion is discarded
226
         </li>
227
         <li>
228
            $type == 'datetime', 'timestamp' or 'dt'<br />
229
            Attempts to conver the string to date and time using strtotime, returning it in format YYYY-MM-DD HH:MM:SS, enclosed in single quotes.
230
         </li>
231
         <li>
232
            $type == 'integer', 'i', 'float', 'f'<br />
233
            uses intval and floatval respectively to convert the string to a number. Returns the result as an unenclosed string.
234
         </li>
235
         <li>
236
            $type == 'bool', 'boolean' or 'b'<br />
237
            Looks for the character 0, 'f' or 'n'. If one of those is the first character in the string, returns 0, else returns 1. Note this can be overridden by setting the paramters $falsetrue when calling the function.
238
         </li>
239
      </ul>
240
      <p>
241
         A note on the date and datetime. This uses strtotime, which is a very powerful function, accepting strings like 'tomorrow at 5pm' and, in most cases, correctly calculating the result. However, the functionality of this is at times erratic.
242
      </p>
243
      <h2>public function getOneRow( $sql = null )</h2>
244
      <p>
245
         executes a query, returning only the first row as an associative array
246
      </p>
247
      <h2>public function getOneDBValue( $sql = null )</h2>
248
      <p>
249
         executes query, returning only the first column of the first row found.
250
      </p>
251
      <h2>Convenience functions</h2>
252
      <ul>
253
         <li>
254
            public static function error2String( $error )<br />
255
            when passed an array of errors, returns a string of newline terminated, human readable text. One line per array entry
256
         </li>
257
         <li>
258
            load( $parameters ) and save()<br />
259
            public functions which simply retrieve or set $this->parameters
260
         </li>
261
         <li>
262
            __set( $name, $value) and __get( $name )<br />
263
            public functions which retrieve or set individual members of the $this->parameters array
264
         </li>
265
      </ul>
266
   </body>
267
</html>