/[drupal]/contributions/sandbox/crell/pdo.php
ViewVC logotype

Contents of /contributions/sandbox/crell/pdo.php

Parent Directory Parent Directory | Revision Log Revision Log | View Revision Graph Revision Graph


Revision 1.15 - (show annotations) (download) (as text)
Sun Dec 9 06:43:47 2007 UTC (23 months, 2 weeks ago) by crell
Branch: MAIN
CVS Tags: HEAD
Changes since 1.14: +59 -30 lines
File MIME type: text/x-php
- Finish adding $options array to query configuration.
1 <?php
2
3 error_reporting(E_ALL | E_STRICT);
4
5 define('DEBUG', TRUE);
6
7 function debug($msg, $label = 'DEBUG', $stealth = FALSE) {
8 if (defined('DEBUG') && DEBUG) {
9 if (is_bool($msg)) $msg = $msg ? 'TRUE' : 'FALSE';
10 $display = $stealth ? ' style="display: none;"' : '';
11 $backtrace = debug_backtrace();
12 $debug = array();
13 $stack = (isset($backtrace[1]['class']) ? "{$backtrace[1]['class']}::" : '')
14 . (isset($backtrace[1]['function']) ? "{$backtrace[1]['function']}" : '');
15 if ($stack) $debug[] = $stack;
16 $debug[] = "Line {$backtrace[0]['line']} of {$backtrace[0]['file']}";
17 $debug = implode('<br />', $debug);
18 print "<pre{$display}>{$label}: {$debug}:<br />" . print_r($msg, 1) . "</pre><br />\n";
19 }
20 }
21
22 //debug(False, 'Something here', TRUE);
23
24 /**
25 * Base Database API class.
26 *
27 * This class provides a Drupal-specific extension of the PDO database abstraction class in PHP.
28 * All database access calls should be issued statically against this class. It acts as a Factory,
29 * returning the appropriate child class for a specific database implmentation based on the
30 * values of the global $db_url array.
31 *
32 */
33 abstract class Database extends PDO {
34
35 /**
36 * The format for getting a random number in this particular database.
37 *
38 * @var string
39 */
40 static public $rand;
41
42 /**
43 * The date() foramt code needed to convert a unix timestamp int
44 * the native timestamp format of this database.
45 *
46 * @var unknown_type
47 */
48 static public $timestamp;
49
50 /**
51 * The date() format code to turn a unix timestamp into
52 * the native date format of the database.
53 *
54 * @var string
55 */
56 static public $time;
57
58 static protected $connections = array();
59
60 static protected $dbUrls = NULL;
61
62 static $activeKey = 'default';
63
64 function __construct($dsn, $username = "", $password = "", $driver_options = array()) {
65 $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION; // Because the other methods don't seem to work right.
66 parent::__construct($dsn, $username, $password, $driver_options);
67 $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('DBStatement' , array($this)));
68 }
69
70 public static function getActiveConnection($target = 'default') {
71 return self::getConnection(self::$activeKey, $target);
72 }
73
74 public static function setActiveConnection($key = 'default') {
75 $old_key = self::$activeKey;
76 self::$activeKey = $key;
77 return $old_key;
78 }
79
80 /**
81 * Parse out the database URLs specified in the config file
82 * and specify defaults where necessary.
83 */
84 protected static function parseUrls() {
85 global $db_url;
86 self::$dbUrls = $db_url;
87 if (! is_array(self::$dbUrls)) {
88 self::$dbUrls = array('default' => self::$dbUrls);
89 }
90 foreach (self::$dbUrls as $index => $url) {
91 if (! is_array(self::$dbUrls[$index])) {
92 self::$dbUrls[$index] = array('default' => $url);
93 }
94 foreach (self::$dbUrls[$index] as $target => $value) {
95 // Each target can also be an array. If it is, we select one entry at random to be
96 // target for this request. That allows us to have multiple slave servers.
97 if (is_array($value)) {
98 self::$dbUrls[$index][$target] = self::$dbUrls[$index][$target][mt_rand(0, count(self::$dbUrls[$index][$target]) - 1)];
99 }
100 }
101 }
102 }
103
104 /**
105 * Open a connection to the server specified by the given
106 * key and target.
107 *
108 * @param $key
109 * @param $target
110 */
111 protected static function openConnection($key, $target) {
112 // Expand out the connection URLs to extended syntax. It makes the parsing
113 // later easier if we take care of all of the conditionals here, once.
114 if (! isset(self::$db_urls)) {
115 self::parseUrls();
116 }
117
118 // If the requested database does not exist then it is an unrecoverable error.
119 // If the requested target does not exist, however, we fall back to the default
120 // target. The target is typically either "default" or "slave", indicating to
121 // use a slave SQL server if one is available. If it's not available, then the
122 // default/master server is the correct server to use.
123 if (! isset(self::$dbUrls[$key])) {
124 throw new Exception('DB does not exist');
125 }
126 if (! isset(self::$dbUrls[$key][$target])) {
127 $target = 'default';
128 }
129
130 // Parse out the connection URL so we can build our connection object.
131 $url = parse_url(self::$dbUrls[$key][$target]);
132 // Decode url-encoded information in the db connection string.
133 $url['user'] = urldecode($url['user']);
134 // Test if database url has a password.
135 $url['pass'] = isset($url['pass']) ? urldecode($url['pass']) : '';
136 $url['host'] = urldecode($url['host']);
137 $url['path'] = urldecode($url['path']);
138 // Allow for non-standard port.
139 if (isset($url['port'])) {
140 $url['host'] = $url['host'] . ':' . $url['port'];
141 }
142
143 // Each supported database type has its own child class for database-specific operations.
144 // Instantiate and return an object of that class, which will still present a unified API.
145 $db_type = 'Database_' . $url['scheme'];
146 try {
147 self::$connections[$key][$target] = new $db_type($url);
148 } catch (PDOException $e) {
149 debug($e->getMessage());
150 //watchdog('database', $e->getMessage());
151 // print some sort of error here.
152 }
153 }
154
155 public static function getConnection($key = 'default', $target = 'default') {
156
157 if (! isset(self::$connections[$key][$target])) {
158 self::openConnection($key, $target);
159 }
160
161 return self::$connections[$key][$target];
162 }
163
164 /**
165 * Append a database prefix to all tables in a query.
166 *
167 * Queries sent to Drupal should wrap all table names in curly brackets. This
168 * function searches for this syntax and adds Drupal's table prefix to all
169 * tables, allowing Drupal to coexist with other systems in the same database if
170 * necessary.
171 *
172 * @param $sql
173 * A string containing a partial or entire SQL query.
174 * @return
175 * The properly-prefixed string.
176 */
177 protected function prefixTables($sql) {
178 global $db_prefix;
179
180 if (is_array($db_prefix)) {
181 if (array_key_exists('default', $db_prefix)) {
182 $tmp = $db_prefix;
183 unset($tmp['default']);
184 foreach ($tmp as $key => $val) {
185 $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
186 }
187 return strtr($sql, array('{' => $db_prefix['default'] , '}' => ''));
188 } else {
189 foreach ($db_prefix as $key => $val) {
190 $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
191 }
192 return strtr($sql, array('{' => '' , '}' => ''));
193 }
194 } else {
195 return strtr($sql, array('{' => $db_prefix , '}' => ''));
196 }
197 }
198
199 protected function runQuery($query, Array $args, $options, $return_affected = FALSE) {
200
201 static $statements = array();
202
203 $query = self::prefixTables($query);
204
205 // Cache each prepared statement, keyed by the query itself. This way,
206 // we get the benefit of prepared statement caching without any extra
207 // work by the module author.
208 if (! isset($statements[$query])) {
209 $statements[$query] = $this->prepare($query);
210 }
211
212 $options += Database::defaultOptions();
213 $statements[$query]->execute($args, $options);
214
215
216 if ($return_affected) {
217 return $statements[$query]->rowCount();
218 } else {
219 return $statements[$query];
220 }
221 }
222
223 /**
224 * Execute a SELECT query on this database object.
225 *
226 * @param $query
227 * A string containing an SQL query.
228 * @param $args
229 * An array of values to substitute into the query at placeholder markers.
230 * @param $options
231 * An array of options on the query. This array is assumed to have all
232 * values populated.
233 * @return
234 * A database query result resource, or FALSE if the query was not executed
235 * correctly.
236 */
237 public function query($query, Array $args, Array $options) {
238
239 // Backward compatibility hack, temporary.
240 $query = str_replace(array('%d' , '%f' , '%b' , "'%s'"), '?', $query);
241
242 return $this->runQuery($query, $args, $options);
243 }
244
245 /**
246 * Run an insert query on this database object.
247 *
248 * @param $table
249 * The database table on which to run the insert query.
250 * @param $fields
251 * An associative array of the values to insert. The keys are the
252 * fields, and the corresponding values are the values to insert.
253 * @return
254 * A database query result resource, or FALSE if the query was not
255 * executed correctly.
256 *
257 */
258 function insert($table, Array $fields, $delay = FALSE) {
259 $insert_fields = array_keys($fields);
260 $insert_values = array_values($fields);
261
262 $placeholders = array_fill(0, count($insert_values), '?');
263
264 $num_affected = $this->runQuery('INSERT INTO {' . $table . '} (' . implode(',', $insert_fields) . ') VALUES (' . implode(',', $placeholders) . ')', $insert_values, array(), TRUE);
265 return $this->lastInsertId();
266 }
267
268 /**
269 * Build the WHERE portion of an SQL query, based on the specified values.
270 *
271 * @todo Add support for non-equality comparisons.
272 * @param $where
273 * Associative array of rules in the WHERE clause. If a key in the array
274 * is numeric, the value is taken as a literal rule. If it is non-numeric,
275 * then it is assumed to be a field name and the corresponding value is the
276 * value that it must hold.
277 * @param $where_type
278 * Whether the values of the WHERE clause should be ANDed or ORed together.
279 *
280 * As an example, this $where clause would be translated as follows:
281 * $where = array('name'=>'foo', 'type'=>'page', 'created < 1147567877')
282 *
283 * WHERE (name='foo') AND ('type'='page') AND (created < 1147567877')
284 * @return
285 * An array containing the where clause with sprintf() markers, and
286 * an array of values to substitute for them.
287 */
288 static function where(Array $where, $where_type = 'AND', $where_keyword = TRUE) {
289 $params = array();
290 $args = array();
291 foreach ($where as $key => $value) {
292 if (is_numeric($key)) {
293 $params[] = $value;
294 } else {
295 switch ($key) {
296 case 'or':
297 list ($sub_params, $sub_args) = self::where($value, 'OR', FALSE);
298 $params[] = ' (' . $sub_params . ') ';
299 $args = array_merge($args, $sub_args);
300 break;
301 case 'and':
302 list ($sub_params, $sub_args) = self::where($value, 'AND', FALSE);
303 $params[] = ' (' . $sub_params . ') ';
304 $args = array_merge($args, $sub_args);
305 break;
306 case 'not':
307 list ($sub_params, $sub_args) = self::where($value, 'AND', FALSE);
308 $params[] = ' NOT (' . $sub_params . ') ';
309 $args = array_merge($args, $sub_args);
310 break;
311 case '<':
312 $operator = '<';
313 $params[] = ' (' . key($value) . $operator . '?) ';
314 $args[] = current($value);
315 break;
316 case '>':
317 $operator = '>';
318 $params[] = ' (' . key($value) . $operator . '?) ';
319 $args[] = current($value);
320 break;
321 case '<=':
322 $operator = '<=';
323 $params[] = ' (' . key($value) . $operator . '?) ';
324 $args[] = current($value);
325 break;
326 case '>=':
327 $operator = '>=';
328 $params[] = ' (' . key($value) . $operator . '?) ';
329 $args[] = current($value);
330 break;
331 default:
332 $operator = '=';
333 if (is_array($value)) {
334 $params[] = ' (' . $key . ' IN (' . array_fill(0, count($value), '?');
335 array_merge($args, $value);
336 } else {
337 $params[] = ' (' . $key . $operator . '?) ';
338 $args[] = $value;
339 }
340 break;
341 }
342 }
343 }
344
345 $return = '';
346 if (sizeof($params)) {
347 $return = ($where_keyword ? ' WHERE ' : ' ') . implode($where_type, $params);
348 }
349
350 return array($return , $args);
351 }
352
353 /**
354 * Run an update query on this database object.
355 *
356 * @param $table
357 * The database table on which to run the update query.
358 * @param $fields
359 * An associative array of the values to update. The keys are the
360 * fields, and the corresponding values are the values to update to.
361 * @param $where
362 * The where rules for this update query.
363 * @param $where_type
364 * Whether to AND or OR the where rules together.
365 * @return
366 * A database query result resource, or FALSE if the query was not
367 * executed correctly.
368 *
369 */
370 function update($table, Array $fields, Array $where, $where_type = 'AND') {
371
372 $update_values = array();
373 $flat_fields = array();
374
375 foreach ($fields as $field => $value) {
376 $update_values[] = $value;
377 $flat_fields[] = $field . '=?';
378 }
379
380 list ($where_string, $where_values) = self::where($where, $where_type);
381
382 $sql = 'UPDATE {' . $table . '} SET ' . implode(', ', $flat_fields) . $where_string;
383
384 return $this->runQuery($sql, array_merge($update_values, $where_values), array(), TRUE);
385 }
386
387 /**
388 * Run a replace query on this database object.
389 *
390 * Depending on the database, that could be separate delete/insert queries
391 * or a single "insert ... on duplicate update ..." query, or something else.
392 * Note that the $where clause must be a simple AND-based equality array, or
393 * it will fail.
394 *
395 * @param $table
396 * The database table on which to run the update query.
397 * @param $fields
398 * An associative array of the values to update. The keys are the
399 * fields, and the corresponding values are the values to update to.
400 * @param $where
401 * The where rules for this update query.
402 * @param $where_type
403 * Whether to AND or OR the where rules together.
404 * @return
405 * A database query result resource, or FALSE if the query was not
406 * executed correctly.
407 *
408 */
409 function replace($table, Array $fields, Array $where) {
410
411 // The following trivial method should be replaced with a database-specific
412 // mechanism if one exists.
413 $num_deleted = $this->delete($table, $where);
414 $fields += $where;
415 $num_inserted = $this->insert($table, $fields);
416 return $num_deleted + $num_inserted;
417 }
418
419 /**
420 * Run a delete query on this database object.
421 *
422 * @param $table
423 * The database table on which to run the delete query.
424 * @param $where
425 * The where rules for this delete query.
426 * @param $where_type
427 * Whether to AND or OR the where rules together.
428 * @return
429 * A database query result resource, or FALSE if the query was not
430 * executed correctly.
431 *
432 */
433 function delete($table, Array $where, $where_type = 'AND') {
434 list ($where_string, $where_values) = self::where($where, $where_type);
435 $sql = 'DELETE FROM {' . $table . '} ' . $where_string;
436 return $this->runQuery($sql, $where_values, array(), TRUE);
437 }
438
439 /**
440 * Return the default query options for any given query.
441 *
442 * @return
443 * An array of default query options.
444 */
445 static function defaultOptions() {
446 return array(
447 'target' => 'default',
448 'database' => NULL,
449 'fetch' => PDO::FETCH_OBJ,
450 );
451 }
452
453 /**
454 * Runs a limited-range query on this database object.
455 *
456 * Use this as a substitute for ->query() when a subset of the query is to be
457 * returned.
458 * User-supplied arguments to the query should be passed in as separate parameters
459 * so that they can be properly escaped to avoid SQL injection attacks.
460 *
461 * @param $query
462 * A string containing an SQL query.
463 * @param $args
464 * An array of values to substitute into the query at placeholder markers.
465 * @param $from
466 * The first result row to return.
467 * @param $count
468 * The maximum number of result rows to return.
469 * @param $options
470 * An array of options on the query. This array is assumed to have all
471 * values populated.
472 * @return
473 * A database query result resource, or FALSE if the query was not executed
474 * correctly.
475 */
476 abstract function queryRange($query, Array $args, $from, $count, Array $options);
477
478 /**
479 * Runs a SELECT query and stores its results in a temporary table.
480 *
481 * Use this as a substitute for db_query() when the results need to stored
482 * in a temporary table. Temporary tables exist for the duration of the page
483 * request.
484 * User-supplied arguments to the query should be passed in as separate parameters
485 * so that they can be properly escaped to avoid SQL injection attacks.
486 *
487 * Note that if you need to know how many results were returned, you should do
488 * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows() does
489 * not give consistent result across different database types in this case.
490 *
491 * @param $query
492 * A string containing a normal SELECT SQL query.
493 * @param $args
494 * An array of values to substitute into the query at placeholder markers.
495 * @param $tablename
496 * The name of the temporary table to select into. This name will not be
497 * prefixed as there is no risk of collision.
498 * @return
499 * A database query result resource, or FALSE if the query was not executed
500 * correctly.
501 */
502 abstract function queryTemporary($query, Array $args, $tablename);
503
504 }
505
506 class Database_mysql extends Database {
507
508 public static $rand = 'RAND()';
509 public static $timestamp = 'Y-m-d h:i:s';
510
511 function __construct($url) {
512 parent::__construct('mysql:host=' . $url['host'] . ';dbname=' . substr($url['path'], 1), $url['user'], $url['pass'], array(
513 PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE , // So we don't have to mess around with cursors.
514 PDO::ATTR_EMULATE_PREPARES => TRUE)// Because MySQL's prepared statements skip the query cache, because it's dumb.
515 );
516 }
517
518 function queryRange($query, Array $args, $from, $count, Array $options) {
519 // Backward compatibility hack, temporary.
520 $query = str_replace(array('%d' , '%f' , '%b' , "'%s'"), '?', $query);
521
522 return $this->runQuery($query . ' LIMIT ' . $from . ', ' . $count, $args, $options);
523 }
524
525 function queryTemporary($query, Array $args, $tablename) {
526 $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' . $tablename . ' Engine=HEAP SELECT', $this->prefixTables($query));
527
528 return $this->runQuery($query, $args, $options);
529 }
530
531 function replace($table, Array $fields, Array $where) {
532
533 $insert_list = $fields + $where;
534
535 $insert_fields = array_keys($insert_list);
536 $insert_values = array_values($insert_list);
537
538 $placeholders = array_fill(0, count($insert_values), '?');
539
540 $update_values = array();
541 $flat_fields = array();
542
543 foreach ($fields as $field => $value) {
544 $insert_values[] = $value;
545 $flat_fields[] = $field . '=?';
546 }
547
548 return $this->runQuery('INSERT INTO {' . $table . '} (' . implode(',', $insert_fields) . ') VALUES (' . implode(',', $placeholders) . ') ON DUPLICATE KEY UPDATE ' . implode(', ', $flat_fields), $insert_values, array(), TRUE);
549 }
550 }
551
552 /**
553 * Not yet functional demo of how one would implement an Oracle or similar driver.
554 *
555 */
556 class Database_oci extends Database {
557
558 function __construct($url) {
559 parent::__construct('oci:dbname=' . substr($url['path'], 1), $url['user'], $url['pass'], array());
560 }
561
562 function insert($table, $fields, $delay = FALSE) {
563 $insert_fields = array_keys($fields);
564 $insert_values = array_values($fields);
565
566 $schema = schema_get_schema($table);
567
568 $i = 1;
569 foreach ($fields as $field => $value) {
570 $type = in_array($schema['fields'][$field]['type'], array('text' , 'blob')) ? PDO::PARAM_LOB : NULL;
571 $placeholders[] = in_array($schema['fields'][$field]['type'], array('text' , 'blob')) ? 'EMPTY_BLOB()' : '?';
572 $statement->bindParam($i++, $value, $type);
573 }
574
575 $sql = $this->prefixTables('INSERT INTO {' . $table . '} (' . implode(',', $insert_fields) . ') VALUES (' . implode(',', $placeholders) . ')');
576 $statement = $this->prepare($sql);
577
578 $statement->beginTransaction();
579 $statement->execute();
580 $statement->commit();
581
582 return $statement;
583 }
584
585 function queryRange($query, Array $args, $from, $count, Array $options) {
586
587 }
588
589 function queryTemporary($query, Array $args, $tablename) {
590
591 }
592 }
593
594 class DBStatement extends PDOStatement {
595
596 public $dbh;
597
598 protected function __construct($dbh) {
599 $this->dbh = $dbh;
600 $this->setFetchMode(PDO::FETCH_OBJ);
601 }
602
603 public function execute($args, $options) {
604 if (is_string($options['fetch'])) {
605 $this->setFetchMode(PDO::FETCH_CLASS, $options['fetch']);
606 }
607 else {
608 $this->setFetchMode($options['fetch']);
609 }
610 parent::execute($args);
611 }
612
613 public function fetchCol($index = 0) {
614 return $this->fetchAll(PDO::FETCH_COLUMN, $index);
615 }
616
617 public function fetchAllAssoc($key) {
618 $return = array();
619 foreach ($this as $record) {
620 $return[$record->$key] = $record;
621 }
622 return $return;
623 }
624
625 public function fetchOne($index = 0) {
626 return $this->fetchColumn($index);
627 }
628
629 /**
630 * Fetches the next row and returns it as an associative array.
631 *
632 * This method corresponds to PDOStatement::fetchObject(),
633 * but for associative arrays. Why objects get a method of their
634 * own and arrays do not, I do not know.
635 *
636 */
637 public function fetchAssoc() {
638 return $this->fetch(PDO::FETCH_ASSOC);
639 }
640 }
641
642 class Dummy { }
643
644 /**
645 * The following utility functions are simply convenience wrappers.
646 * They should never, ever have any database-specific code in them.
647 */
648
649 function db_query($query, Array $args = array(), Array $options = array()) {
650 // Get default options.
651 $options += Database::defaultOptions();
652
653 if (isset($options['database'])) {
654 return Database::getConnection($options['database'], $options['target'])->query($query, $args, $options);
655 }
656 return Database::getActiveConnection($options['target'])->query($query, $args, $options);
657 }
658
659 function db_query_range($query, Array $args, $from = 0, $count = 0, Array $options = array()) {
660 // Get default options.
661 $options += Database::defaultOptions();
662
663 if (isset($options['database'])) {
664 return Database::getConnection($options['database'], $options['target'])->queryRange($query, $args, $from, $count, $options);
665 }
666 return Database::getActiveConnection($options['target'])->queryRange($query, $args, $from, $count, $options);
667 }
668
669 function db_query_temporary($query, Array $args, $tablename) {
670 return Database::getActiveConnection()->queryTemporary($query, $args, $tablename);
671 }
672
673 function db_insert($table, Array $fields = array(), $delay = FALSE) {
674 return Database::getActiveConnection()->insert($table, $fields, $delay);
675 }
676
677 function db_update($table, Array $fields = array(), $where = array(), $where_type = 'AND', $delay = FALSE) {
678 return Database::getActiveConnection()->update($table, $fields, $where, $where_type, $delay);
679 }
680
681 function db_replace($table, Array $fields = array(), $where = array()) {
682 return Database::getActiveConnection()->replace($table, $fields, $where);
683 }
684
685 function db_delete($table, Array $where = array(), $where_type = 'AND', $delay = FALSE) {
686 return Database::getActiveConnection()->delete($table, $where, $where_type, $delay);
687 }
688
689 function db_set_active($key = 'default') {
690 Database::setActiveConnection($key);
691 }
692
693 // For temporary backward compatibility only.
694 function db_fetch_object(DBStatement $statement) {
695 return $statement->fetch(PDO::FETCH_OBJ);
696 }
697
698 function db_fetch_array(DBStatement $statement) {
699 return $statement->fetch(PDO::FETCH_BOTH);
700 }
701
702 /**
703 * Some testing and demo code.
704 */
705
706 /**
707 * The $db_url array, which defines our various and sundry connections.
708 */
709 $db_url['default']['default'] = 'mysql://test:test@localhost/drupal6test';
710 $db_url['default']['slave'][] = 'mysql://test:test@localhost/drupal6test';
711 $db_url['default']['slave'][] = 'mysql://test:test@localhost/drupal6test';
712 $db_url['default']['slave'][] = 'mysql://test:test@localhost/drupal6test';
713
714
715 db_query("SELECT * FROM {system} WHERE status=:status", array(':status' => 1), array('target' => 'slave', 'fetch' => 'Dummy'));
716
717
718 $result = db_query("SELECT * FROM {system} WHERE status=:status", array(':status' => 1));
719 foreach ($result as $record) {
720 //debug($record);
721 }
722
723 $result2 = db_query("SELECT * FROM {system} WHERE status=:status", array(':status' => 1), array('target' => 'slave'));
724 //debug($result2->fetchAll());
725
726 $result3 = db_query("SELECT * FROM {system} WHERE status='%s'", array(1));
727 //debug($result3->fetchAll());
728
729
730 db_query("DROP TABLE IF EXISTS {test}");
731 db_query("CREATE TABLE {test} (
732 id INT AUTO_INCREMENT NOT NULL,
733 name VARCHAR(255) NOT NULL DEFAULT '',
734 age INT NOT NULL DEFAULT 0,
735 PRIMARY KEY (id)
736 );");
737
738 db_insert('test', array('name' => 'Larry' , 'age' => 26), TRUE);
739 debug(db_insert('test', array('name' => 'George' , 'age' => 28)));
740 db_insert('test', array('name' => 'Dan' , 'age' => 24));
741 db_insert('test', array('name' => 'Robert' , 'age' => 22));
742 db_insert('test', array('name' => 'Bill' , 'age' => 20));
743
744 debug(db_query("SELECT * FROM {test}")->fetchAll());
745
746 debug(db_delete('test', array('age' => 24)));
747
748 debug(db_query("SELECT * FROM {test}")->fetchAll());
749
750 $fields['name'] = 'Jimmy';
751 $where = array(
752 'name' => 'Larry',
753 'not' => array('age' => 26),
754 'or' => array('age' => 20)
755 );
756
757 debug(db_update('test', $fields, $where));
758
759 $where = array('<' => array('age' => 26));
760 debug(db_update('test', $fields, $where));
761
762 debug(db_query_range("SELECT * FROM {test} WHERE age >= ? ORDER BY age", array(20), 0, 3)->fetchAll());
763
764 //db_query_temporary("SELECT * FROM {test} WHERE age >= ? ORDER BY age", array(24), 'temp');
765 //debug(db_query("SHOW TABLES")->fetchAll());
766 //debug(db_query("SELECT * from temp"));
767
768
769 $fields = array('name' => 'Jimmy' , 'age' => 21);
770 $where = array('id' => 1);
771 db_replace('test', $fields, $where);
772
773 debug(db_query("SELECT * FROM {test}")->fetchAll());
774
775 debug(db_query_range("SELECT * FROM {test} WHERE age >= ? ORDER BY age", array(20), 0, 3));
776
777 $where = array('name' => 'Larry' , 'not' => array('age' => 26) , 'or' => array('age' => 20 , 'name' => 'Bob') , '<' => array('age' => 26) , 'name' => array('John' , 'Paul' , 'George' , 'Ringo') , 'NOT' => array('or' => array('age' => 24 , 'name' => 'George' , '>=' => array('age' => 20))));
778
779 debug(db_query("SELECT * FROM {system} WHERE name='user'")->fetchOne());
780
781 debug(db_query("SELECT * FROM {system} WHERE type='module'")->fetchAssoc('name'));

  ViewVC Help
Powered by ViewVC 1.1.2