/
PDO.php
executable file
·432 lines (393 loc) · 11.4 KB
/
PDO.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
<?php
/**
* PDO Driver
* @file RedBean/PDO.php
* @description PDO Driver
* This Driver implements the RedBean Driver API
* @author Desfrenes
* @author G.J.G.T. de Mooij
* @license BSD
*
*
* (c) Desfrenes & Gabor de Mooij
* This source file is subject to the BSD/GPLv2 License that is bundled
* with this source code in the file license.txt.
*
*/
class RedBean_Driver_PDO implements RedBean_Driver {
/**
* Contains database DSN for connecting to database.
* @var string
*/
protected $dsn;
/**
* Whether we are in debugging mode or not.
* @var boolean
*/
protected $debug = false;
/**
* Holds the PDO instance.
* @var PDO
*/
protected $pdo;
/**
* Holds integer number of affected rows from latest query
* if driver supports this feature.
* @var integer
*/
protected $affected_rows;
/**
* Holds result resource.
* @var integer
*/
protected $rs;
/**
* Contains arbitrary connection data.
* @var array
*/
protected $connectInfo = array();
/**
* Whether you want to use classic String Only binding -
* backward compatibility.
* @var bool
*/
public $flagUseStringOnlyBinding = false;
/**
* Whether we are currently connected or not.
* This flag is being used to delay the connection until necessary.
* Delaying connections is a good practice to speed up scripts that
* don't need database connectivity but for some reason want to
* init RedbeanPHP.
* @var boolean
*/
protected $isConnected = false;
/**
* Constructor. You may either specify dsn, user and password or
* just give an existing PDO connection.
* Examples:
* $driver = new RedBean_Driver_PDO($dsn, $user, $password);
* $driver = new RedBean_Driver_PDO($existingConnection);
*
* @param string|PDO $dsn database connection string
* @param string $user optional
* @param string $pass optional
*
* @return void
*/
public function __construct($dsn, $user = NULL, $pass = NULL) {
if ($dsn instanceof PDO) {
$this->pdo = $dsn;
$this->isConnected = true;
$this->pdo->setAttribute(1002, 'SET NAMES utf8');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
// make sure that the dsn at least contains the type
$this->dsn = $this->getDatabaseType();
} else {
$this->dsn = $dsn;
$this->connectInfo = array( "pass"=>$pass, "user"=>$user );
}
}
/**
* Establishes a connection to the database using PHP PDO
* functionality. If a connection has already been established this
* method will simply return directly. This method also turns on
* UTF8 for the database and PDO-ERRMODE-EXCEPTION as well as
* PDO-FETCH-ASSOC.
*
* @return void
*/
public function connect() {
if ($this->isConnected) return;
$user = $this->connectInfo["user"];
$pass = $this->connectInfo["pass"];
//PDO::MYSQL_ATTR_INIT_COMMAND
$this->pdo = new PDO(
$this->dsn,
$user,
$pass,
array(1002 => 'SET NAMES utf8',
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
)
);
$this->pdo->setAttribute(PDO::ATTR_STRINGIFY_FETCHES, TRUE);
$this->isConnected = true;
}
/**
* Binds parameters. This method binds parameters to a PDOStatement for
* Query Execution. This method binds parameters as NULL, INTEGER or STRING
* and supports both named keys and question mark keys.
*
* @param PDOStatement $s PDO Statement instance
* @param array $aValues values that need to get bound to the statement
*
* @return void
*/
protected function bindParams($s,$aValues) {
foreach($aValues as $key=>&$value) {
if (is_integer($key)) {
if (is_null($value)){
$s->bindValue($key+1,null,PDO::PARAM_NULL);
}elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key+1,$value,PDO::PARAM_INT);
}
else {
$s->bindParam($key+1,$value,PDO::PARAM_STR);
}
}
else {
if (is_null($value)){
$s->bindValue($key,null,PDO::PARAM_NULL);
}
elseif (!$this->flagUseStringOnlyBinding && RedBean_QueryWriter_AQueryWriter::canBeTreatedAsInt($value) && $value < 2147483648) {
$s->bindParam($key,$value,PDO::PARAM_INT);
}
else {
$s->bindParam($key,$value,PDO::PARAM_STR);
}
}
}
}
/**
* Runs a query. Internal function, available for subclasses. This method
* runs the actual SQL query and binds a list of parameters to the query.
* slots. The result of the query will be stored in the protected property
* $rs (always array). The number of rows affected (result of rowcount, if supported by database)
* is stored in protected property $affected_rows. If the debug flag is set
* this function will send debugging output to screen buffer.
*
* @throws RedBean_Exception_SQL
*
* @param string $sql the SQL string to be send to database server
* @param array $aValues the values that need to get bound to the query slots
*/
protected function runQuery($sql,$aValues) {
$this->connect();
if ($this->debug) {
echo "<HR>" . $sql.print_r($aValues,1);
}
try {
if (strpos("pgsql",$this->dsn)===0) {
$s = $this->pdo->prepare($sql, array(PDO::PGSQL_ATTR_DISABLE_NATIVE_PREPARED_STATEMENT => true));
}
else {
$s = $this->pdo->prepare($sql);
}
$this->bindParams( $s, $aValues );
$s->execute();
$this->affected_rows = $s->rowCount();
if ($s->columnCount()) {
$this->rs = $s->fetchAll();
if ($this->debug) echo '<br><b style="color:green">resultset: ' . count($this->rs) . ' rows</b>';
}
else {
$this->rs = array();
}
}catch(PDOException $e) {
//Unfortunately the code field is supposed to be int by default (php)
//So we need a property to convey the SQL State code.
$x = new RedBean_Exception_SQL( $e->getMessage(), 0);
$x->setSQLState( $e->getCode() );
throw $x;
}
}
/**
* Runs a query and fetches results as a multi dimensional array.
*
* @param string $sql SQL to be executed
*
* @return array $results result
*/
public function GetAll( $sql, $aValues=array() ) {
$this->runQuery($sql,$aValues);
return $this->rs;
}
/**
* Runs a query and fetches results as a column.
*
* @param string $sql SQL Code to execute
*
* @return array $results Resultset
*/
public function GetCol($sql, $aValues=array()) {
$rows = $this->GetAll($sql,$aValues);
$cols = array();
if ($rows && is_array($rows) && count($rows)>0) {
foreach ($rows as $row) {
$cols[] = array_shift($row);
}
}
return $cols;
}
/**
* Runs a query an returns results as a single cell.
*
* @param string $sql SQL to execute
*
* @return mixed $cellvalue result cell
*/
public function GetCell($sql, $aValues=array()) {
$arr = $this->GetAll($sql,$aValues);
$row1 = array_shift($arr);
$col1 = array_shift($row1);
return $col1;
}
/**
* Runs a query and returns a flat array containing the values of
* one row.
*
* @param string $sql SQL to execute
*
* @return array $row result row
*/
public function GetRow($sql, $aValues=array()) {
$arr = $this->GetAll($sql, $aValues);
return array_shift($arr);
}
/**
* Executes SQL code and allows key-value binding.
* This function allows you to provide an array with values to bind
* to query parameters. For instance you can bind values to question
* marks in the query. Each value in the array corresponds to the
* question mark in the query that matches the position of the value in the
* array. You can also bind values using explicit keys, for instance
* array(":key"=>123) will bind the integer 123 to the key :key in the
* SQL. This method has no return value.
*
* @param string $sql SQL Code to execute
* @param array $aValues Values to bind to SQL query
*
* @return void
*/
public function Execute( $sql, $aValues=array() ) {
$this->runQuery($sql,$aValues);
return $this->affected_rows;
}
/**
* Escapes a string for use in SQL using the currently selected
* PDO driver.
*
* @param string $string string to be escaped
*
* @return string $string escaped string
*/
public function Escape( $str ) {
$this->connect();
return substr(substr($this->pdo->quote($str), 1), 0, -1);
}
/**
* Returns the latest insert ID if driver does support this
* feature.
*
* @return integer $id primary key ID
*/
public function GetInsertID() {
$this->connect();
return (int) $this->pdo->lastInsertId();
}
/**
* Returns the number of rows affected by the most recent query
* if the currently selected PDO driver supports this feature.
*
* @return integer $numOfRows number of rows affected
*/
public function Affected_Rows() {
$this->connect();
return (int) $this->affected_rows;
}
/**
* Toggles debug mode. In debug mode the driver will print all
* SQL to the screen together with some information about the
* results. All SQL code that passes through the driver will be
* passes on to the screen for inspection.
* This method has no return value.
*
* @param boolean $trueFalse turn on/off
*
* @return void
*/
public function setDebugMode( $tf ) {
$this->connect();
$this->debug = (bool)$tf;
}
/**
* Starts a transaction.
* This method is part of the transaction mechanism of
* RedBeanPHP. All queries in a transaction are executed together.
* In case of an error all commands will be rolled back so none of the
* SQL in the transaction will affect the DB. Using transactions is
* considered best practice.
* This method has no return value.
*
* @return void
*/
public function StartTrans() {
$this->connect();
$this->pdo->beginTransaction();
}
/**
* Commits a transaction.
* This method is part of the transaction mechanism of
* RedBeanPHP. All queries in a transaction are executed together.
* In case of an error all commands will be rolled back so none of the
* SQL in the transaction will affect the DB. Using transactions is
* considered best practice.
* This method has no return value.
*
* @return void
*/
public function CommitTrans() {
$this->connect();
$this->pdo->commit();
}
/**
* Rolls back a transaction.
* This method is part of the transaction mechanism of
* RedBeanPHP. All queries in a transaction are executed together.
* In case of an error all commands will be rolled back so none of the
* SQL in the transaction will affect the DB. Using transactions is
* considered best practice.
* This method has no return value.
*
* @return void
*/
public function FailTrans() {
$this->connect();
$this->pdo->rollback();
}
/**
* Returns the name of the database type/brand: i.e. mysql, db2 etc.
*
* @return string $typeName database identification
*/
public function getDatabaseType() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
}
/**
* Returns the version number of the database.
*
* @return mixed $version version number of the database
*/
public function getDatabaseVersion() {
$this->connect();
return $this->pdo->getAttribute(PDO::ATTR_CLIENT_VERSION);
}
/**
* Returns the underlying PHP PDO instance.
*
* @return PDO $pdo PDO instance used by PDO wrapper
*/
public function getPDO() {
$this->connect();
return $this->pdo;
}
/**
* Closes database connection by destructing PDO.
*/
public function close() {
$this->pdo = null;
$this->isConnected = false;
}
}