Automatically exported from code.google.com/p/planningalerts
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

2158 lines
68 KiB

  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * Contains the DB_common base class
  5. *
  6. * PHP versions 4 and 5
  7. *
  8. * LICENSE: This source file is subject to version 3.0 of the PHP license
  9. * that is available through the world-wide-web at the following URI:
  10. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  11. * the PHP License and are unable to obtain it through the web, please
  12. * send a note to license@php.net so we can mail you a copy immediately.
  13. *
  14. * @category Database
  15. * @package DB
  16. * @author Stig Bakken <ssb@php.net>
  17. * @author Tomas V.V. Cox <cox@idecnet.com>
  18. * @author Daniel Convissor <danielc@php.net>
  19. * @copyright 1997-2005 The PHP Group
  20. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  21. * @version CVS: $Id: common.php,v 1.1 2005/08/01 06:21:02 dancoulter Exp $
  22. * @link http://pear.php.net/package/DB
  23. */
  24. /**
  25. * Obtain the PEAR class so it can be extended from
  26. */
  27. require_once 'PEAR.php';
  28. /**
  29. * DB_common is the base class from which each database driver class extends
  30. *
  31. * All common methods are declared here. If a given DBMS driver contains
  32. * a particular method, that method will overload the one here.
  33. *
  34. * @category Database
  35. * @package DB
  36. * @author Stig Bakken <ssb@php.net>
  37. * @author Tomas V.V. Cox <cox@idecnet.com>
  38. * @author Daniel Convissor <danielc@php.net>
  39. * @copyright 1997-2005 The PHP Group
  40. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  41. * @version Release: @package_version@
  42. * @link http://pear.php.net/package/DB
  43. */
  44. class DB_common extends PEAR
  45. {
  46. // {{{ properties
  47. /**
  48. * The current default fetch mode
  49. * @var integer
  50. */
  51. var $fetchmode = DB_FETCHMODE_ORDERED;
  52. /**
  53. * The name of the class into which results should be fetched when
  54. * DB_FETCHMODE_OBJECT is in effect
  55. *
  56. * @var string
  57. */
  58. var $fetchmode_object_class = 'stdClass';
  59. /**
  60. * Was a connection present when the object was serialized()?
  61. * @var bool
  62. * @see DB_common::__sleep(), DB_common::__wake()
  63. */
  64. var $was_connected = null;
  65. /**
  66. * The most recently executed query
  67. * @var string
  68. */
  69. var $last_query = '';
  70. /**
  71. * Run-time configuration options
  72. *
  73. * The 'optimize' option has been deprecated. Use the 'portability'
  74. * option instead.
  75. *
  76. * @var array
  77. * @see DB_common::setOption()
  78. */
  79. var $options = array(
  80. 'result_buffering' => 500,
  81. 'persistent' => false,
  82. 'ssl' => false,
  83. 'debug' => 0,
  84. 'seqname_format' => '%s_seq',
  85. 'autofree' => false,
  86. 'portability' => DB_PORTABILITY_NONE,
  87. 'optimize' => 'performance', // Deprecated. Use 'portability'.
  88. );
  89. /**
  90. * The parameters from the most recently executed query
  91. * @var array
  92. * @since Property available since Release 1.7.0
  93. */
  94. var $last_parameters = array();
  95. /**
  96. * The elements from each prepared statement
  97. * @var array
  98. */
  99. var $prepare_tokens = array();
  100. /**
  101. * The data types of the various elements in each prepared statement
  102. * @var array
  103. */
  104. var $prepare_types = array();
  105. /**
  106. * The prepared queries
  107. * @var array
  108. */
  109. var $prepared_queries = array();
  110. // }}}
  111. // {{{ DB_common
  112. /**
  113. * This constructor calls <kbd>$this->PEAR('DB_Error')</kbd>
  114. *
  115. * @return void
  116. */
  117. function DB_common()
  118. {
  119. $this->PEAR('DB_Error');
  120. }
  121. // }}}
  122. // {{{ __sleep()
  123. /**
  124. * Automatically indicates which properties should be saved
  125. * when PHP's serialize() function is called
  126. *
  127. * @return array the array of properties names that should be saved
  128. */
  129. function __sleep()
  130. {
  131. if ($this->connection) {
  132. // Don't disconnect(), people use serialize() for many reasons
  133. $this->was_connected = true;
  134. } else {
  135. $this->was_connected = false;
  136. }
  137. if (isset($this->autocommit)) {
  138. return array('autocommit',
  139. 'dbsyntax',
  140. 'dsn',
  141. 'features',
  142. 'fetchmode',
  143. 'fetchmode_object_class',
  144. 'options',
  145. 'was_connected',
  146. );
  147. } else {
  148. return array('dbsyntax',
  149. 'dsn',
  150. 'features',
  151. 'fetchmode',
  152. 'fetchmode_object_class',
  153. 'options',
  154. 'was_connected',
  155. );
  156. }
  157. }
  158. // }}}
  159. // {{{ __wakeup()
  160. /**
  161. * Automatically reconnects to the database when PHP's unserialize()
  162. * function is called
  163. *
  164. * The reconnection attempt is only performed if the object was connected
  165. * at the time PHP's serialize() function was run.
  166. *
  167. * @return void
  168. */
  169. function __wakeup()
  170. {
  171. if ($this->was_connected) {
  172. $this->connect($this->dsn, $this->options);
  173. }
  174. }
  175. // }}}
  176. // {{{ __toString()
  177. /**
  178. * Automatic string conversion for PHP 5
  179. *
  180. * @return string a string describing the current PEAR DB object
  181. *
  182. * @since Method available since Release 1.7.0
  183. */
  184. function __toString()
  185. {
  186. $info = strtolower(get_class($this));
  187. $info .= ': (phptype=' . $this->phptype .
  188. ', dbsyntax=' . $this->dbsyntax .
  189. ')';
  190. if ($this->connection) {
  191. $info .= ' [connected]';
  192. }
  193. return $info;
  194. }
  195. // }}}
  196. // {{{ toString()
  197. /**
  198. * DEPRECATED: String conversion method
  199. *
  200. * @return string a string describing the current PEAR DB object
  201. *
  202. * @deprecated Method deprecated in Release 1.7.0
  203. */
  204. function toString()
  205. {
  206. return $this->__toString();
  207. }
  208. // }}}
  209. // {{{ quoteString()
  210. /**
  211. * DEPRECATED: Quotes a string so it can be safely used within string
  212. * delimiters in a query
  213. *
  214. * @param string $string the string to be quoted
  215. *
  216. * @return string the quoted string
  217. *
  218. * @see DB_common::quoteSmart(), DB_common::escapeSimple()
  219. * @deprecated Method deprecated some time before Release 1.2
  220. */
  221. function quoteString($string)
  222. {
  223. $string = $this->quote($string);
  224. if ($string{0} == "'") {
  225. return substr($string, 1, -1);
  226. }
  227. return $string;
  228. }
  229. // }}}
  230. // {{{ quote()
  231. /**
  232. * DEPRECATED: Quotes a string so it can be safely used in a query
  233. *
  234. * @param string $string the string to quote
  235. *
  236. * @return string the quoted string or the string <samp>NULL</samp>
  237. * if the value submitted is <kbd>null</kbd>.
  238. *
  239. * @see DB_common::quoteSmart(), DB_common::escapeSimple()
  240. * @deprecated Deprecated in release 1.6.0
  241. */
  242. function quote($string = null)
  243. {
  244. return ($string === null) ? 'NULL'
  245. : "'" . str_replace("'", "''", $string) . "'";
  246. }
  247. // }}}
  248. // {{{ quoteIdentifier()
  249. /**
  250. * Quotes a string so it can be safely used as a table or column name
  251. *
  252. * Delimiting style depends on which database driver is being used.
  253. *
  254. * NOTE: just because you CAN use delimited identifiers doesn't mean
  255. * you SHOULD use them. In general, they end up causing way more
  256. * problems than they solve.
  257. *
  258. * Portability is broken by using the following characters inside
  259. * delimited identifiers:
  260. * + backtick (<kbd>`</kbd>) -- due to MySQL
  261. * + double quote (<kbd>"</kbd>) -- due to Oracle
  262. * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
  263. *
  264. * Delimited identifiers are known to generally work correctly under
  265. * the following drivers:
  266. * + mssql
  267. * + mysql
  268. * + mysqli
  269. * + oci8
  270. * + odbc(access)
  271. * + odbc(db2)
  272. * + pgsql
  273. * + sqlite
  274. * + sybase (must execute <kbd>set quoted_identifier on</kbd> sometime
  275. * prior to use)
  276. *
  277. * InterBase doesn't seem to be able to use delimited identifiers
  278. * via PHP 4. They work fine under PHP 5.
  279. *
  280. * @param string $str the identifier name to be quoted
  281. *
  282. * @return string the quoted identifier
  283. *
  284. * @since Method available since Release 1.6.0
  285. */
  286. function quoteIdentifier($str)
  287. {
  288. return '"' . str_replace('"', '""', $str) . '"';
  289. }
  290. // }}}
  291. // {{{ quoteSmart()
  292. /**
  293. * Formats input so it can be safely used in a query
  294. *
  295. * The output depends on the PHP data type of input and the database
  296. * type being used.
  297. *
  298. * @param mixed $in the data to be formatted
  299. *
  300. * @return mixed the formatted data. The format depends on the input's
  301. * PHP type:
  302. * <ul>
  303. * <li>
  304. * <kbd>input</kbd> -> <samp>returns</samp>
  305. * </li>
  306. * <li>
  307. * <kbd>null</kbd> -> the string <samp>NULL</samp>
  308. * </li>
  309. * <li>
  310. * <kbd>integer</kbd> or <kbd>double</kbd> -> the unquoted number
  311. * </li>
  312. * <li>
  313. * <kbd>bool</kbd> -> output depends on the driver in use
  314. * Most drivers return integers: <samp>1</samp> if
  315. * <kbd>true</kbd> or <samp>0</samp> if
  316. * <kbd>false</kbd>.
  317. * Some return strings: <samp>TRUE</samp> if
  318. * <kbd>true</kbd> or <samp>FALSE</samp> if
  319. * <kbd>false</kbd>.
  320. * Finally one returns strings: <samp>T</samp> if
  321. * <kbd>true</kbd> or <samp>F</samp> if
  322. * <kbd>false</kbd>. Here is a list of each DBMS,
  323. * the values returned and the suggested column type:
  324. * <ul>
  325. * <li>
  326. * <kbd>dbase</kbd> -> <samp>T/F</samp>
  327. * (<kbd>Logical</kbd>)
  328. * </li>
  329. * <li>
  330. * <kbd>fbase</kbd> -> <samp>TRUE/FALSE</samp>
  331. * (<kbd>BOOLEAN</kbd>)
  332. * </li>
  333. * <li>
  334. * <kbd>ibase</kbd> -> <samp>1/0</samp>
  335. * (<kbd>SMALLINT</kbd>) [1]
  336. * </li>
  337. * <li>
  338. * <kbd>ifx</kbd> -> <samp>1/0</samp>
  339. * (<kbd>SMALLINT</kbd>) [1]
  340. * </li>
  341. * <li>
  342. * <kbd>msql</kbd> -> <samp>1/0</samp>
  343. * (<kbd>INTEGER</kbd>)
  344. * </li>
  345. * <li>
  346. * <kbd>mssql</kbd> -> <samp>1/0</samp>
  347. * (<kbd>BIT</kbd>)
  348. * </li>
  349. * <li>
  350. * <kbd>mysql</kbd> -> <samp>1/0</samp>
  351. * (<kbd>TINYINT(1)</kbd>)
  352. * </li>
  353. * <li>
  354. * <kbd>mysqli</kbd> -> <samp>1/0</samp>
  355. * (<kbd>TINYINT(1)</kbd>)
  356. * </li>
  357. * <li>
  358. * <kbd>oci8</kbd> -> <samp>1/0</samp>
  359. * (<kbd>NUMBER(1)</kbd>)
  360. * </li>
  361. * <li>
  362. * <kbd>odbc</kbd> -> <samp>1/0</samp>
  363. * (<kbd>SMALLINT</kbd>) [1]
  364. * </li>
  365. * <li>
  366. * <kbd>pgsql</kbd> -> <samp>TRUE/FALSE</samp>
  367. * (<kbd>BOOLEAN</kbd>)
  368. * </li>
  369. * <li>
  370. * <kbd>sqlite</kbd> -> <samp>1/0</samp>
  371. * (<kbd>INTEGER</kbd>)
  372. * </li>
  373. * <li>
  374. * <kbd>sybase</kbd> -> <samp>1/0</samp>
  375. * (<kbd>TINYINT(1)</kbd>)
  376. * </li>
  377. * </ul>
  378. * [1] Accommodate the lowest common denominator because not all
  379. * versions of have <kbd>BOOLEAN</kbd>.
  380. * </li>
  381. * <li>
  382. * other (including strings and numeric strings) ->
  383. * the data with single quotes escaped by preceeding
  384. * single quotes, backslashes are escaped by preceeding
  385. * backslashes, then the whole string is encapsulated
  386. * between single quotes
  387. * </li>
  388. * </ul>
  389. *
  390. * @see DB_common::escapeSimple()
  391. * @since Method available since Release 1.6.0
  392. */
  393. function quoteSmart($in)
  394. {
  395. if (is_int($in) || is_double($in)) {
  396. return $in;
  397. } elseif (is_bool($in)) {
  398. return $in ? 1 : 0;
  399. } elseif (is_null($in)) {
  400. return 'NULL';
  401. } else {
  402. return "'" . $this->escapeSimple($in) . "'";
  403. }
  404. }
  405. // }}}
  406. // {{{ escapeSimple()
  407. /**
  408. * Escapes a string according to the current DBMS's standards
  409. *
  410. * In SQLite, this makes things safe for inserts/updates, but may
  411. * cause problems when performing text comparisons against columns
  412. * containing binary data. See the
  413. * {@link http://php.net/sqlite_escape_string PHP manual} for more info.
  414. *
  415. * @param string $str the string to be escaped
  416. *
  417. * @return string the escaped string
  418. *
  419. * @see DB_common::quoteSmart()
  420. * @since Method available since Release 1.6.0
  421. */
  422. function escapeSimple($str)
  423. {
  424. return str_replace("'", "''", $str);
  425. }
  426. // }}}
  427. // {{{ provides()
  428. /**
  429. * Tells whether the present driver supports a given feature
  430. *
  431. * @param string $feature the feature you're curious about
  432. *
  433. * @return bool whether this driver supports $feature
  434. */
  435. function provides($feature)
  436. {
  437. return $this->features[$feature];
  438. }
  439. // }}}
  440. // {{{ setFetchMode()
  441. /**
  442. * Sets the fetch mode that should be used by default for query results
  443. *
  444. * @param integer $fetchmode DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC
  445. * or DB_FETCHMODE_OBJECT
  446. * @param string $object_class the class name of the object to be returned
  447. * by the fetch methods when the
  448. * DB_FETCHMODE_OBJECT mode is selected.
  449. * If no class is specified by default a cast
  450. * to object from the assoc array row will be
  451. * done. There is also the posibility to use
  452. * and extend the 'DB_row' class.
  453. *
  454. * @see DB_FETCHMODE_ORDERED, DB_FETCHMODE_ASSOC, DB_FETCHMODE_OBJECT
  455. */
  456. function setFetchMode($fetchmode, $object_class = 'stdClass')
  457. {
  458. switch ($fetchmode) {
  459. case DB_FETCHMODE_OBJECT:
  460. $this->fetchmode_object_class = $object_class;
  461. case DB_FETCHMODE_ORDERED:
  462. case DB_FETCHMODE_ASSOC:
  463. $this->fetchmode = $fetchmode;
  464. break;
  465. default:
  466. return $this->raiseError('invalid fetchmode mode');
  467. }
  468. }
  469. // }}}
  470. // {{{ setOption()
  471. /**
  472. * Sets run-time configuration options for PEAR DB
  473. *
  474. * Options, their data types, default values and description:
  475. * <ul>
  476. * <li>
  477. * <var>autofree</var> <kbd>boolean</kbd> = <samp>false</samp>
  478. * <br />should results be freed automatically when there are no
  479. * more rows?
  480. * </li><li>
  481. * <var>result_buffering</var> <kbd>integer</kbd> = <samp>500</samp>
  482. * <br />how many rows of the result set should be buffered?
  483. * <br />In mysql: mysql_unbuffered_query() is used instead of
  484. * mysql_query() if this value is 0. (Release 1.7.0)
  485. * <br />In oci8: this value is passed to ocisetprefetch().
  486. * (Release 1.7.0)
  487. * </li><li>
  488. * <var>debug</var> <kbd>integer</kbd> = <samp>0</samp>
  489. * <br />debug level
  490. * </li><li>
  491. * <var>persistent</var> <kbd>boolean</kbd> = <samp>false</samp>
  492. * <br />should the connection be persistent?
  493. * </li><li>
  494. * <var>portability</var> <kbd>integer</kbd> = <samp>DB_PORTABILITY_NONE</samp>
  495. * <br />portability mode constant (see below)
  496. * </li><li>
  497. * <var>seqname_format</var> <kbd>string</kbd> = <samp>%s_seq</samp>
  498. * <br />the sprintf() format string used on sequence names. This
  499. * format is applied to sequence names passed to
  500. * createSequence(), nextID() and dropSequence().
  501. * </li><li>
  502. * <var>ssl</var> <kbd>boolean</kbd> = <samp>false</samp>
  503. * <br />use ssl to connect?
  504. * </li>
  505. * </ul>
  506. *
  507. * -----------------------------------------
  508. *
  509. * PORTABILITY MODES
  510. *
  511. * These modes are bitwised, so they can be combined using <kbd>|</kbd>
  512. * and removed using <kbd>^</kbd>. See the examples section below on how
  513. * to do this.
  514. *
  515. * <samp>DB_PORTABILITY_NONE</samp>
  516. * turn off all portability features
  517. *
  518. * This mode gets automatically turned on if the deprecated
  519. * <var>optimize</var> option gets set to <samp>performance</samp>.
  520. *
  521. *
  522. * <samp>DB_PORTABILITY_LOWERCASE</samp>
  523. * convert names of tables and fields to lower case when using
  524. * <kbd>get*()</kbd>, <kbd>fetch*()</kbd> and <kbd>tableInfo()</kbd>
  525. *
  526. * This mode gets automatically turned on in the following databases
  527. * if the deprecated option <var>optimize</var> gets set to
  528. * <samp>portability</samp>:
  529. * + oci8
  530. *
  531. *
  532. * <samp>DB_PORTABILITY_RTRIM</samp>
  533. * right trim the data output by <kbd>get*()</kbd> <kbd>fetch*()</kbd>
  534. *
  535. *
  536. * <samp>DB_PORTABILITY_DELETE_COUNT</samp>
  537. * force reporting the number of rows deleted
  538. *
  539. * Some DBMS's don't count the number of rows deleted when performing
  540. * simple <kbd>DELETE FROM tablename</kbd> queries. This portability
  541. * mode tricks such DBMS's into telling the count by adding
  542. * <samp>WHERE 1=1</samp> to the end of <kbd>DELETE</kbd> queries.
  543. *
  544. * This mode gets automatically turned on in the following databases
  545. * if the deprecated option <var>optimize</var> gets set to
  546. * <samp>portability</samp>:
  547. * + fbsql
  548. * + mysql
  549. * + mysqli
  550. * + sqlite
  551. *
  552. *
  553. * <samp>DB_PORTABILITY_NUMROWS</samp>
  554. * enable hack that makes <kbd>numRows()</kbd> work in Oracle
  555. *
  556. * This mode gets automatically turned on in the following databases
  557. * if the deprecated option <var>optimize</var> gets set to
  558. * <samp>portability</samp>:
  559. * + oci8
  560. *
  561. *
  562. * <samp>DB_PORTABILITY_ERRORS</samp>
  563. * makes certain error messages in certain drivers compatible
  564. * with those from other DBMS's
  565. *
  566. * + mysql, mysqli: change unique/primary key constraints
  567. * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT
  568. *
  569. * + odbc(access): MS's ODBC driver reports 'no such field' as code
  570. * 07001, which means 'too few parameters.' When this option is on
  571. * that code gets mapped to DB_ERROR_NOSUCHFIELD.
  572. * DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD
  573. *
  574. * <samp>DB_PORTABILITY_NULL_TO_EMPTY</samp>
  575. * convert null values to empty strings in data output by get*() and
  576. * fetch*(). Needed because Oracle considers empty strings to be null,
  577. * while most other DBMS's know the difference between empty and null.
  578. *
  579. *
  580. * <samp>DB_PORTABILITY_ALL</samp>
  581. * turn on all portability features
  582. *
  583. * -----------------------------------------
  584. *
  585. * Example 1. Simple setOption() example
  586. * <code>
  587. * $db->setOption('autofree', true);
  588. * </code>
  589. *
  590. * Example 2. Portability for lowercasing and trimming
  591. * <code>
  592. * $db->setOption('portability',
  593. * DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM);
  594. * </code>
  595. *
  596. * Example 3. All portability options except trimming
  597. * <code>
  598. * $db->setOption('portability',
  599. * DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM);
  600. * </code>
  601. *
  602. * @param string $option option name
  603. * @param mixed $value value for the option
  604. *
  605. * @return int DB_OK on success. A DB_Error object on failure.
  606. *
  607. * @see DB_common::$options
  608. */
  609. function setOption($option, $value)
  610. {
  611. if (isset($this->options[$option])) {
  612. $this->options[$option] = $value;
  613. /*
  614. * Backwards compatibility check for the deprecated 'optimize'
  615. * option. Done here in case settings change after connecting.
  616. */
  617. if ($option == 'optimize') {
  618. if ($value == 'portability') {
  619. switch ($this->phptype) {
  620. case 'oci8':
  621. $this->options['portability'] =
  622. DB_PORTABILITY_LOWERCASE |
  623. DB_PORTABILITY_NUMROWS;
  624. break;
  625. case 'fbsql':
  626. case 'mysql':
  627. case 'mysqli':
  628. case 'sqlite':
  629. $this->options['portability'] =
  630. DB_PORTABILITY_DELETE_COUNT;
  631. break;
  632. }
  633. } else {
  634. $this->options['portability'] = DB_PORTABILITY_NONE;
  635. }
  636. }
  637. return DB_OK;
  638. }
  639. return $this->raiseError("unknown option $option");
  640. }
  641. // }}}
  642. // {{{ getOption()
  643. /**
  644. * Returns the value of an option
  645. *
  646. * @param string $option the option name you're curious about
  647. *
  648. * @return mixed the option's value
  649. */
  650. function getOption($option)
  651. {
  652. if (isset($this->options[$option])) {
  653. return $this->options[$option];
  654. }
  655. return $this->raiseError("unknown option $option");
  656. }
  657. // }}}
  658. // {{{ prepare()
  659. /**
  660. * Prepares a query for multiple execution with execute()
  661. *
  662. * Creates a query that can be run multiple times. Each time it is run,
  663. * the placeholders, if any, will be replaced by the contents of
  664. * execute()'s $data argument.
  665. *
  666. * Three types of placeholders can be used:
  667. * + <kbd>?</kbd> scalar value (i.e. strings, integers). The system
  668. * will automatically quote and escape the data.
  669. * + <kbd>!</kbd> value is inserted 'as is'
  670. * + <kbd>&</kbd> requires a file name. The file's contents get
  671. * inserted into the query (i.e. saving binary
  672. * data in a db)
  673. *
  674. * Example 1.
  675. * <code>
  676. * $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
  677. * $data = array(
  678. * "John's text",
  679. * "'it''s good'",
  680. * 'filename.txt'
  681. * );
  682. * $res = $db->execute($sth, $data);
  683. * </code>
  684. *
  685. * Use backslashes to escape placeholder characters if you don't want
  686. * them to be interpreted as placeholders:
  687. * <pre>
  688. * "UPDATE foo SET col=? WHERE col='over \& under'"
  689. * </pre>
  690. *
  691. * With some database backends, this is emulated.
  692. *
  693. * {@internal ibase and oci8 have their own prepare() methods.}}
  694. *
  695. * @param string $query the query to be prepared
  696. *
  697. * @return mixed DB statement resource on success. A DB_Error object
  698. * on failure.
  699. *
  700. * @see DB_common::execute()
  701. */
  702. function prepare($query)
  703. {
  704. $tokens = preg_split('/((?<!\\\)[&?!])/', $query, -1,
  705. PREG_SPLIT_DELIM_CAPTURE);
  706. $token = 0;
  707. $types = array();
  708. $newtokens = array();
  709. foreach ($tokens as $val) {
  710. switch ($val) {
  711. case '?':
  712. $types[$token++] = DB_PARAM_SCALAR;
  713. break;
  714. case '&':
  715. $types[$token++] = DB_PARAM_OPAQUE;
  716. break;
  717. case '!':
  718. $types[$token++] = DB_PARAM_MISC;
  719. break;
  720. default:
  721. $newtokens[] = preg_replace('/\\\([&?!])/', "\\1", $val);
  722. }
  723. }
  724. $this->prepare_tokens[] = &$newtokens;
  725. end($this->prepare_tokens);
  726. $k = key($this->prepare_tokens);
  727. $this->prepare_types[$k] = $types;
  728. $this->prepared_queries[$k] = implode(' ', $newtokens);
  729. return $k;
  730. }
  731. // }}}
  732. // {{{ autoPrepare()
  733. /**
  734. * Automaticaly generates an insert or update query and pass it to prepare()
  735. *
  736. * @param string $table the table name
  737. * @param array $table_fields the array of field names
  738. * @param int $mode a type of query to make:
  739. * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  740. * @param string $where for update queries: the WHERE clause to
  741. * append to the SQL statement. Don't
  742. * include the "WHERE" keyword.
  743. *
  744. * @return resource the query handle
  745. *
  746. * @uses DB_common::prepare(), DB_common::buildManipSQL()
  747. */
  748. function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT,
  749. $where = false)
  750. {
  751. $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
  752. if (DB::isError($query)) {
  753. return $query;
  754. }
  755. return $this->prepare($query);
  756. }
  757. // }}}
  758. // {{{ autoExecute()
  759. /**
  760. * Automaticaly generates an insert or update query and call prepare()
  761. * and execute() with it
  762. *
  763. * @param string $table the table name
  764. * @param array $fields_values the associative array where $key is a
  765. * field name and $value its value
  766. * @param int $mode a type of query to make:
  767. * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  768. * @param string $where for update queries: the WHERE clause to
  769. * append to the SQL statement. Don't
  770. * include the "WHERE" keyword.
  771. *
  772. * @return mixed a new DB_result object for successful SELECT queries
  773. * or DB_OK for successul data manipulation queries.
  774. * A DB_Error object on failure.
  775. *
  776. * @uses DB_common::autoPrepare(), DB_common::execute()
  777. */
  778. function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT,
  779. $where = false)
  780. {
  781. $sth = $this->autoPrepare($table, array_keys($fields_values), $mode,
  782. $where);
  783. if (DB::isError($sth)) {
  784. return $sth;
  785. }
  786. $ret =& $this->execute($sth, array_values($fields_values));
  787. $this->freePrepared($sth);
  788. return $ret;
  789. }
  790. // }}}
  791. // {{{ buildManipSQL()
  792. /**
  793. * Produces an SQL query string for autoPrepare()
  794. *
  795. * Example:
  796. * <pre>
  797. * buildManipSQL('table_sql', array('field1', 'field2', 'field3'),
  798. * DB_AUTOQUERY_INSERT);
  799. * </pre>
  800. *
  801. * That returns
  802. * <samp>
  803. * INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?)
  804. * </samp>
  805. *
  806. * NOTES:
  807. * - This belongs more to a SQL Builder class, but this is a simple
  808. * facility.
  809. * - Be carefull! If you don't give a $where param with an UPDATE
  810. * query, all the records of the table will be updated!
  811. *
  812. * @param string $table the table name
  813. * @param array $table_fields the array of field names
  814. * @param int $mode a type of query to make:
  815. * DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  816. * @param string $where for update queries: the WHERE clause to
  817. * append to the SQL statement. Don't
  818. * include the "WHERE" keyword.
  819. *
  820. * @return string the sql query for autoPrepare()
  821. */
  822. function buildManipSQL($table, $table_fields, $mode, $where = false)
  823. {
  824. if (count($table_fields) == 0) {
  825. return $this->raiseError(DB_ERROR_NEED_MORE_DATA);
  826. }
  827. $first = true;
  828. switch ($mode) {
  829. case DB_AUTOQUERY_INSERT:
  830. $values = '';
  831. $names = '';
  832. foreach ($table_fields as $value) {
  833. if ($first) {
  834. $first = false;
  835. } else {
  836. $names .= ',';
  837. $values .= ',';
  838. }
  839. $names .= $value;
  840. $values .= '?';
  841. }
  842. return "INSERT INTO $table ($names) VALUES ($values)";
  843. case DB_AUTOQUERY_UPDATE:
  844. $set = '';
  845. foreach ($table_fields as $value) {
  846. if ($first) {
  847. $first = false;
  848. } else {
  849. $set .= ',';
  850. }
  851. $set .= "$value = ?";
  852. }
  853. $sql = "UPDATE $table SET $set";
  854. if ($where) {
  855. $sql .= " WHERE $where";
  856. }
  857. return $sql;
  858. default:
  859. return $this->raiseError(DB_ERROR_SYNTAX);
  860. }
  861. }
  862. // }}}
  863. // {{{ execute()
  864. /**
  865. * Executes a DB statement prepared with prepare()
  866. *
  867. * Example 1.
  868. * <code>
  869. * $sth = $db->prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)');
  870. * $data = array(
  871. * "John's text",
  872. * "'it''s good'",
  873. * 'filename.txt'
  874. * );
  875. * $res =& $db->execute($sth, $data);
  876. * </code>
  877. *
  878. * @param resource $stmt a DB statement resource returned from prepare()
  879. * @param mixed $data array, string or numeric data to be used in
  880. * execution of the statement. Quantity of items
  881. * passed must match quantity of placeholders in
  882. * query: meaning 1 placeholder for non-array
  883. * parameters or 1 placeholder per array element.
  884. *
  885. * @return mixed a new DB_result object for successful SELECT queries
  886. * or DB_OK for successul data manipulation queries.
  887. * A DB_Error object on failure.
  888. *
  889. * {@internal ibase and oci8 have their own execute() methods.}}
  890. *
  891. * @see DB_common::prepare()
  892. */
  893. function &execute($stmt, $data = array())
  894. {
  895. $realquery = $this->executeEmulateQuery($stmt, $data);
  896. if (DB::isError($realquery)) {
  897. return $realquery;
  898. }
  899. $result = $this->simpleQuery($realquery);
  900. if ($result === DB_OK || DB::isError($result)) {
  901. return $result;
  902. } else {
  903. $tmp =& new DB_result($this, $result);
  904. return $tmp;
  905. }
  906. }
  907. // }}}
  908. // {{{ executeEmulateQuery()
  909. /**
  910. * Emulates executing prepared statements if the DBMS not support them
  911. *
  912. * @param resource $stmt a DB statement resource returned from execute()
  913. * @param mixed $data array, string or numeric data to be used in
  914. * execution of the statement. Quantity of items
  915. * passed must match quantity of placeholders in
  916. * query: meaning 1 placeholder for non-array
  917. * parameters or 1 placeholder per array element.
  918. *
  919. * @return mixed a string containing the real query run when emulating
  920. * prepare/execute. A DB_Error object on failure.
  921. *
  922. * @access protected
  923. * @see DB_common::execute()
  924. */
  925. function executeEmulateQuery($stmt, $data = array())
  926. {
  927. $stmt = (int)$stmt;
  928. $data = (array)$data;
  929. $this->last_parameters = $data;
  930. if (count($this->prepare_types[$stmt]) != count($data)) {
  931. $this->last_query = $this->prepared_queries[$stmt];
  932. return $this->raiseError(DB_ERROR_MISMATCH);
  933. }
  934. $realquery = $this->prepare_tokens[$stmt][0];
  935. $i = 0;
  936. foreach ($data as $value) {
  937. if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) {
  938. $realquery .= $this->quoteSmart($value);
  939. } elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) {
  940. $fp = @fopen($value, 'rb');
  941. if (!$fp) {
  942. return $this->raiseError(DB_ERROR_ACCESS_VIOLATION);
  943. }
  944. $realquery .= $this->quoteSmart(fread($fp, filesize($value)));
  945. fclose($fp);
  946. } else {
  947. $realquery .= $value;
  948. }
  949. $realquery .= $this->prepare_tokens[$stmt][++$i];
  950. }
  951. return $realquery;
  952. }
  953. // }}}
  954. // {{{ executeMultiple()
  955. /**
  956. * Performs several execute() calls on the same statement handle
  957. *
  958. * $data must be an array indexed numerically
  959. * from 0, one execute call is done for every "row" in the array.
  960. *
  961. * If an error occurs during execute(), executeMultiple() does not
  962. * execute the unfinished rows, but rather returns that error.
  963. *
  964. * @param resource $stmt query handle from prepare()
  965. * @param array $data numeric array containing the
  966. * data to insert into the query
  967. *
  968. * @return int DB_OK on success. A DB_Error object on failure.
  969. *
  970. * @see DB_common::prepare(), DB_common::execute()
  971. */
  972. function executeMultiple($stmt, $data)
  973. {
  974. foreach ($data as $value) {
  975. $res =& $this->execute($stmt, $value);
  976. if (DB::isError($res)) {
  977. return $res;
  978. }
  979. }
  980. return DB_OK;
  981. }
  982. // }}}
  983. // {{{ freePrepared()
  984. /**
  985. * Frees the internal resources associated with a prepared query
  986. *
  987. * @param resource $stmt the prepared statement's PHP resource
  988. * @param bool $free_resource should the PHP resource be freed too?
  989. * Use false if you need to get data
  990. * from the result set later.
  991. *
  992. * @return bool TRUE on success, FALSE if $result is invalid
  993. *
  994. * @see DB_common::prepare()
  995. */
  996. function freePrepared($stmt, $free_resource = true)
  997. {
  998. $stmt = (int)$stmt;
  999. if (isset($this->prepare_tokens[$stmt])) {
  1000. unset($this->prepare_tokens[$stmt]);
  1001. unset($this->prepare_types[$stmt]);
  1002. unset($this->prepared_queries[$stmt]);
  1003. return true;
  1004. }
  1005. return false;
  1006. }
  1007. // }}}
  1008. // {{{ modifyQuery()
  1009. /**
  1010. * Changes a query string for various DBMS specific reasons
  1011. *
  1012. * It is defined here to ensure all drivers have this method available.
  1013. *
  1014. * @param string $query the query string to modify
  1015. *
  1016. * @return string the modified query string
  1017. *
  1018. * @access protected
  1019. * @see DB_mysql::modifyQuery(), DB_oci8::modifyQuery(),
  1020. * DB_sqlite::modifyQuery()
  1021. */
  1022. function modifyQuery($query)
  1023. {
  1024. return $query;
  1025. }
  1026. // }}}
  1027. // {{{ modifyLimitQuery()
  1028. /**
  1029. * Adds LIMIT clauses to a query string according to current DBMS standards
  1030. *
  1031. * It is defined here to assure that all implementations
  1032. * have this method defined.
  1033. *
  1034. * @param string $query the query to modify
  1035. * @param int $from the row to start to fetching (0 = the first row)
  1036. * @param int $count the numbers of rows to fetch
  1037. * @param mixed $params array, string or numeric data to be used in
  1038. * execution of the statement. Quantity of items
  1039. * passed must match quantity of placeholders in
  1040. * query: meaning 1 placeholder for non-array
  1041. * parameters or 1 placeholder per array element.
  1042. *
  1043. * @return string the query string with LIMIT clauses added
  1044. *
  1045. * @access protected
  1046. */
  1047. function modifyLimitQuery($query, $from, $count, $params = array())
  1048. {
  1049. return $query;
  1050. }
  1051. // }}}
  1052. // {{{ query()
  1053. /**
  1054. * Sends a query to the database server
  1055. *
  1056. * The query string can be either a normal statement to be sent directly
  1057. * to the server OR if <var>$params</var> are passed the query can have
  1058. * placeholders and it will be passed through prepare() and execute().
  1059. *
  1060. * @param string $query the SQL query or the statement to prepare
  1061. * @param mixed $params array, string or numeric data to be used in
  1062. * execution of the statement. Quantity of items
  1063. * passed must match quantity of placeholders in
  1064. * query: meaning 1 placeholder for non-array
  1065. * parameters or 1 placeholder per array element.
  1066. *
  1067. * @return mixed a new DB_result object for successful SELECT queries
  1068. * or DB_OK for successul data manipulation queries.
  1069. * A DB_Error object on failure.
  1070. *
  1071. * @see DB_result, DB_common::prepare(), DB_common::execute()
  1072. */
  1073. function &query($query, $params = array())
  1074. {
  1075. if (sizeof($params) > 0) {
  1076. $sth = $this->prepare($query);
  1077. if (DB::isError($sth)) {
  1078. return $sth;
  1079. }
  1080. $ret =& $this->execute($sth, $params);
  1081. $this->freePrepared($sth, false);
  1082. return $ret;
  1083. } else {
  1084. $this->last_parameters = array();
  1085. $result = $this->simpleQuery($query);
  1086. if ($result === DB_OK || DB::isError($result)) {
  1087. return $result;
  1088. } else {
  1089. $tmp =& new DB_result($this, $result);
  1090. return $tmp;
  1091. }
  1092. }
  1093. }
  1094. // }}}
  1095. // {{{ limitQuery()
  1096. /**
  1097. * Generates and executes a LIMIT query
  1098. *
  1099. * @param string $query the query
  1100. * @param intr $from the row to start to fetching (0 = the first row)
  1101. * @param int $count the numbers of rows to fetch
  1102. * @param mixed $params array, string or numeric data to be used in
  1103. * execution of the statement. Quantity of items
  1104. * passed must match quantity of placeholders in
  1105. * query: meaning 1 placeholder for non-array
  1106. * parameters or 1 placeholder per array element.
  1107. *
  1108. * @return mixed a new DB_result object for successful SELECT queries
  1109. * or DB_OK for successul data manipulation queries.
  1110. * A DB_Error object on failure.
  1111. */
  1112. function &limitQuery($query, $from, $count, $params = array())
  1113. {
  1114. $query = $this->modifyLimitQuery($query, $from, $count, $params);
  1115. if (DB::isError($query)){
  1116. return $query;
  1117. }
  1118. $result =& $this->query($query, $params);
  1119. if (is_a($result, 'DB_result')) {
  1120. $result->setOption('limit_from', $from);
  1121. $result->setOption('limit_count', $count);
  1122. }
  1123. return $result;
  1124. }
  1125. // }}}
  1126. // {{{ getOne()
  1127. /**
  1128. * Fetches the first column of the first row from a query result
  1129. *
  1130. * Takes care of doing the query and freeing the results when finished.
  1131. *
  1132. * @param string $query the SQL query
  1133. * @param mixed $params array, string or numeric data to be used in
  1134. * execution of the statement. Quantity of items
  1135. * passed must match quantity of placeholders in
  1136. * query: meaning 1 placeholder for non-array
  1137. * parameters or 1 placeholder per array element.
  1138. *
  1139. * @return mixed the returned value of the query.
  1140. * A DB_Error object on failure.
  1141. */
  1142. function &getOne($query, $params = array())
  1143. {
  1144. $params = (array)$params;
  1145. // modifyLimitQuery() would be nice here, but it causes BC issues
  1146. if (sizeof($params) > 0) {
  1147. $sth = $this->prepare($query);
  1148. if (DB::isError($sth)) {
  1149. return $sth;
  1150. }
  1151. $res =& $this->execute($sth, $params);
  1152. $this->freePrepared($sth);
  1153. } else {
  1154. $res =& $this->query($query);
  1155. }
  1156. if (DB::isError($res)) {
  1157. return $res;
  1158. }
  1159. $err = $res->fetchInto($row, DB_FETCHMODE_ORDERED);
  1160. $res->free();
  1161. if ($err !== DB_OK) {
  1162. return $err;
  1163. }
  1164. return $row[0];
  1165. }
  1166. // }}}
  1167. // {{{ getRow()
  1168. /**
  1169. * Fetches the first row of data returned from a query result
  1170. *
  1171. * Takes care of doing the query and freeing the results when finished.
  1172. *
  1173. * @param string $query the SQL query
  1174. * @param mixed $params array, string or numeric data to be used in
  1175. * execution of the statement. Quantity of items
  1176. * passed must match quantity of placeholders in
  1177. * query: meaning 1 placeholder for non-array
  1178. * parameters or 1 placeholder per array element.
  1179. * @param int $fetchmode the fetch mode to use
  1180. *
  1181. * @return array the first row of results as an array.
  1182. * A DB_Error object on failure.
  1183. */
  1184. function &getRow($query, $params = array(),
  1185. $fetchmode = DB_FETCHMODE_DEFAULT)
  1186. {
  1187. // compat check, the params and fetchmode parameters used to
  1188. // have the opposite order
  1189. if (!is_array($params)) {
  1190. if (is_array($fetchmode)) {
  1191. if ($params === null) {
  1192. $tmp = DB_FETCHMODE_DEFAULT;
  1193. } else {
  1194. $tmp = $params;
  1195. }
  1196. $params = $fetchmode;
  1197. $fetchmode = $tmp;
  1198. } elseif ($params !== null) {
  1199. $fetchmode = $params;
  1200. $params = array();
  1201. }
  1202. }
  1203. // modifyLimitQuery() would be nice here, but it causes BC issues
  1204. if (sizeof($params) > 0) {
  1205. $sth = $this->prepare($query);
  1206. if (DB::isError($sth)) {
  1207. return $sth;
  1208. }
  1209. $res =& $this->execute($sth, $params);
  1210. $this->freePrepared($sth);
  1211. } else {
  1212. $res =& $this->query($query);
  1213. }
  1214. if (DB::isError($res)) {
  1215. return $res;
  1216. }
  1217. $err = $res->fetchInto($row, $fetchmode);
  1218. $res->free();
  1219. if ($err !== DB_OK) {
  1220. return $err;
  1221. }
  1222. return $row;
  1223. }
  1224. // }}}
  1225. // {{{ getCol()
  1226. /**
  1227. * Fetches a single column from a query result and returns it as an
  1228. * indexed array
  1229. *
  1230. * @param string $query the SQL query
  1231. * @param mixed $col which column to return (integer [column number,
  1232. * starting at 0] or string [column name])
  1233. * @param mixed $params array, string or numeric data to be used in
  1234. * execution of the statement. Quantity of items
  1235. * passed must match quantity of placeholders in
  1236. * query: meaning 1 placeholder for non-array
  1237. * parameters or 1 placeholder per array element.
  1238. *
  1239. * @return array the results as an array. A DB_Error object on failure.
  1240. *
  1241. * @see DB_common::query()
  1242. */
  1243. function &getCol($query, $col = 0, $params = array())
  1244. {
  1245. $params = (array)$params;
  1246. if (sizeof($params) > 0) {
  1247. $sth = $this->prepare($query);
  1248. if (DB::isError($sth)) {
  1249. return $sth;
  1250. }
  1251. $res =& $this->execute($sth, $params);
  1252. $this->freePrepared($sth);
  1253. } else {
  1254. $res =& $this->query($query);
  1255. }
  1256. if (DB::isError($res)) {
  1257. return $res;
  1258. }
  1259. $fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC;
  1260. if (!is_array($row = $res->fetchRow($fetchmode))) {
  1261. $ret = array();
  1262. } else {
  1263. if (!array_key_exists($col, $row)) {
  1264. $ret =& $this->raiseError(DB_ERROR_NOSUCHFIELD);
  1265. } else {
  1266. $ret = array($row[$col]);
  1267. while (is_array($row = $res->fetchRow($fetchmode))) {
  1268. $ret[] = $row[$col];
  1269. }
  1270. }
  1271. }
  1272. $res->free();
  1273. if (DB::isError($row)) {
  1274. $ret = $row;
  1275. }
  1276. return $ret;
  1277. }
  1278. // }}}
  1279. // {{{ getAssoc()
  1280. /**
  1281. * Fetches an entire query result and returns it as an
  1282. * associative array using the first column as the key
  1283. *
  1284. * If the result set contains more than two columns, the value
  1285. * will be an array of the values from column 2-n. If the result
  1286. * set contains only two columns, the returned value will be a
  1287. * scalar with the value of the second column (unless forced to an
  1288. * array with the $force_array parameter). A DB error code is
  1289. * returned on errors. If the result set contains fewer than two
  1290. * columns, a DB_ERROR_TRUNCATED error is returned.
  1291. *
  1292. * For example, if the table "mytable" contains:
  1293. *
  1294. * <pre>
  1295. * ID TEXT DATE
  1296. * --------------------------------
  1297. * 1 'one' 944679408
  1298. * 2 'two' 944679408
  1299. * 3 'three' 944679408
  1300. * </pre>
  1301. *
  1302. * Then the call getAssoc('SELECT id,text FROM mytable') returns:
  1303. * <pre>
  1304. * array(
  1305. * '1' => 'one',
  1306. * '2' => 'two',
  1307. * '3' => 'three',
  1308. * )
  1309. * </pre>
  1310. *
  1311. * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
  1312. * <pre>
  1313. * array(
  1314. * '1' => array('one', '944679408'),
  1315. * '2' => array('two', '944679408'),
  1316. * '3' => array('three', '944679408')
  1317. * )
  1318. * </pre>
  1319. *
  1320. * If the more than one row occurs with the same value in the
  1321. * first column, the last row overwrites all previous ones by
  1322. * default. Use the $group parameter if you don't want to
  1323. * overwrite like this. Example:
  1324. *
  1325. * <pre>
  1326. * getAssoc('SELECT category,id,name FROM mytable', false, null,
  1327. * DB_FETCHMODE_ASSOC, true) returns:
  1328. *
  1329. * array(
  1330. * '1' => array(array('id' => '4', 'name' => 'number four'),
  1331. * array('id' => '6', 'name' => 'number six')
  1332. * ),
  1333. * '9' => array(array('id' => '4', 'name' => 'number four'),
  1334. * array('id' => '6', 'name' => 'number six')
  1335. * )
  1336. * )
  1337. * </pre>
  1338. *
  1339. * Keep in mind that database functions in PHP usually return string
  1340. * values for results regardless of the database's internal type.
  1341. *
  1342. * @param string $query the SQL query
  1343. * @param bool $force_array used only when the query returns
  1344. * exactly two columns. If true, the values
  1345. * of the returned array will be one-element
  1346. * arrays instead of scalars.
  1347. * @param mixed $params array, string or numeric data to be used in
  1348. * execution of the statement. Quantity of
  1349. * items passed must match quantity of
  1350. * placeholders in query: meaning 1
  1351. * placeholder for non-array parameters or
  1352. * 1 placeholder per array element.
  1353. * @param int $fetchmode the fetch mode to use
  1354. * @param bool $group if true, the values of the returned array
  1355. * is wrapped in another array. If the same
  1356. * key value (in the first column) repeats
  1357. * itself, the values will be appended to
  1358. * this array instead of overwriting the
  1359. * existing values.
  1360. *
  1361. * @return array the associative array containing the query results.
  1362. * A DB_Error object on failure.
  1363. */
  1364. function &getAssoc($query, $force_array = false, $params = array(),
  1365. $fetchmode = DB_FETCHMODE_DEFAULT, $group = false)
  1366. {
  1367. $params = (array)$params;
  1368. if (sizeof($params) > 0) {
  1369. $sth = $this->prepare($query);
  1370. if (DB::isError($sth)) {
  1371. return $sth;
  1372. }
  1373. $res =& $this->execute($sth, $params);
  1374. $this->freePrepared($sth);
  1375. } else {
  1376. $res =& $this->query($query);
  1377. }
  1378. if (DB::isError($res)) {
  1379. return $res;
  1380. }
  1381. if ($fetchmode == DB_FETCHMODE_DEFAULT) {
  1382. $fetchmode = $this->fetchmode;
  1383. }
  1384. $cols = $res->numCols();
  1385. if ($cols < 2) {
  1386. $tmp =& $this->raiseError(DB_ERROR_TRUNCATED);
  1387. return $tmp;
  1388. }
  1389. $results = array();
  1390. if ($cols > 2 || $force_array) {
  1391. // return array values
  1392. // XXX this part can be optimized
  1393. if ($fetchmode == DB_FETCHMODE_ASSOC) {
  1394. while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) {
  1395. reset($row);
  1396. $key = current($row);
  1397. unset($row[key($row)]);
  1398. if ($group) {
  1399. $results[$key][] = $row;
  1400. } else {
  1401. $results[$key] = $row;
  1402. }
  1403. }
  1404. } elseif ($fetchmode == DB_FETCHMODE_OBJECT) {
  1405. while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) {
  1406. $arr = get_object_vars($row);
  1407. $key = current($arr);
  1408. if ($group) {
  1409. $results[$key][] = $row;
  1410. } else {
  1411. $results[$key] = $row;
  1412. }
  1413. }
  1414. } else {
  1415. while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
  1416. // we shift away the first element to get
  1417. // indices running from 0 again
  1418. $key = array_shift($row);
  1419. if ($group) {
  1420. $results[$key][] = $row;
  1421. } else {
  1422. $results[$key] = $row;
  1423. }
  1424. }
  1425. }
  1426. if (DB::isError($row)) {
  1427. $results = $row;
  1428. }
  1429. } else {
  1430. // return scalar values
  1431. while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) {
  1432. if ($group) {
  1433. $results[$row[0]][] = $row[1];
  1434. } else {
  1435. $results[$row[0]] = $row[1];
  1436. }
  1437. }
  1438. if (DB::isError($row)) {
  1439. $results = $row;
  1440. }
  1441. }
  1442. $res->free();
  1443. return $results;
  1444. }
  1445. // }}}
  1446. // {{{ getAll()
  1447. /**
  1448. * Fetches all of the rows from a query result
  1449. *
  1450. * @param string $query the SQL query
  1451. * @param mixed $params array, string or numeric data to be used in
  1452. * execution of the statement. Quantity of
  1453. * items passed must match quantity of
  1454. * placeholders in query: meaning 1
  1455. * placeholder for non-array parameters or
  1456. * 1 placeholder per array element.
  1457. * @param int $fetchmode the fetch mode to use:
  1458. * + DB_FETCHMODE_ORDERED
  1459. * + DB_FETCHMODE_ASSOC
  1460. * + DB_FETCHMODE_ORDERED | DB_FETCHMODE_FLIPPED
  1461. * + DB_FETCHMODE_ASSOC | DB_FETCHMODE_FLIPPED
  1462. *
  1463. * @return array the nested array. A DB_Error object on failure.
  1464. */
  1465. function &getAll($query, $params = array(),
  1466. $fetchmode = DB_FETCHMODE_DEFAULT)
  1467. {
  1468. // compat check, the params and fetchmode parameters used to
  1469. // have the opposite order
  1470. if (!is_array($params)) {
  1471. if (is_array($fetchmode)) {
  1472. if ($params === null) {
  1473. $tmp = DB_FETCHMODE_DEFAULT;
  1474. } else {
  1475. $tmp = $params;
  1476. }
  1477. $params = $fetchmode;
  1478. $fetchmode = $tmp;
  1479. } elseif ($params !== null) {
  1480. $fetchmode = $params;
  1481. $params = array();
  1482. }
  1483. }
  1484. if (sizeof($params) > 0) {
  1485. $sth = $this->prepare($query);
  1486. if (DB::isError($sth)) {
  1487. return $sth;
  1488. }
  1489. $res =& $this->execute($sth, $params);
  1490. $this->freePrepared($sth);
  1491. } else {
  1492. $res =& $this->query($query);
  1493. }
  1494. if ($res === DB_OK || DB::isError($res)) {
  1495. return $res;
  1496. }
  1497. $results = array();
  1498. while (DB_OK === $res->fetchInto($row, $fetchmode)) {
  1499. if ($fetchmode & DB_FETCHMODE_FLIPPED) {
  1500. foreach ($row as $key => $val) {
  1501. $results[$key][] = $val;
  1502. }
  1503. } else {
  1504. $results[] = $row;
  1505. }
  1506. }
  1507. $res->free();
  1508. if (DB::isError($row)) {
  1509. $tmp =& $this->raiseError($row);
  1510. return $tmp;
  1511. }
  1512. return $results;
  1513. }
  1514. // }}}
  1515. // {{{ autoCommit()
  1516. /**
  1517. * Enables or disables automatic commits
  1518. *
  1519. * @param bool $onoff true turns it on, false turns it off
  1520. *
  1521. * @return int DB_OK on success. A DB_Error object if the driver
  1522. * doesn't support auto-committing transactions.
  1523. */
  1524. function autoCommit($onoff = false)
  1525. {
  1526. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1527. }
  1528. // }}}
  1529. // {{{ commit()
  1530. /**
  1531. * Commits the current transaction
  1532. *
  1533. * @return int DB_OK on success. A DB_Error object on failure.
  1534. */
  1535. function commit()
  1536. {
  1537. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1538. }
  1539. // }}}
  1540. // {{{ rollback()
  1541. /**
  1542. * Reverts the current transaction
  1543. *
  1544. * @return int DB_OK on success. A DB_Error object on failure.
  1545. */
  1546. function rollback()
  1547. {
  1548. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1549. }
  1550. // }}}
  1551. // {{{ numRows()
  1552. /**
  1553. * Determines the number of rows in a query result
  1554. *
  1555. * @param resource $result the query result idenifier produced by PHP
  1556. *
  1557. * @return int the number of rows. A DB_Error object on failure.
  1558. */
  1559. function numRows($result)
  1560. {
  1561. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1562. }
  1563. // }}}
  1564. // {{{ affectedRows()
  1565. /**
  1566. * Determines the number of rows affected by a data maniuplation query
  1567. *
  1568. * 0 is returned for queries that don't manipulate data.
  1569. *
  1570. * @return int the number of rows. A DB_Error object on failure.
  1571. */
  1572. function affectedRows()
  1573. {
  1574. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1575. }
  1576. // }}}
  1577. // {{{ getSequenceName()
  1578. /**
  1579. * Generates the name used inside the database for a sequence
  1580. *
  1581. * The createSequence() docblock contains notes about storing sequence
  1582. * names.
  1583. *
  1584. * @param string $sqn the sequence's public name
  1585. *
  1586. * @return string the sequence's name in the backend
  1587. *
  1588. * @access protected
  1589. * @see DB_common::createSequence(), DB_common::dropSequence(),
  1590. * DB_common::nextID(), DB_common::setOption()
  1591. */
  1592. function getSequenceName($sqn)
  1593. {
  1594. return sprintf($this->getOption('seqname_format'),
  1595. preg_replace('/[^a-z0-9_.]/i', '_', $sqn));
  1596. }
  1597. // }}}
  1598. // {{{ nextId()
  1599. /**
  1600. * Returns the next free id in a sequence
  1601. *
  1602. * @param string $seq_name name of the sequence
  1603. * @param boolean $ondemand when true, the seqence is automatically
  1604. * created if it does not exist
  1605. *
  1606. * @return int the next id number in the sequence.
  1607. * A DB_Error object on failure.
  1608. *
  1609. * @see DB_common::createSequence(), DB_common::dropSequence(),
  1610. * DB_common::getSequenceName()
  1611. */
  1612. function nextId($seq_name, $ondemand = true)
  1613. {
  1614. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1615. }
  1616. // }}}
  1617. // {{{ createSequence()
  1618. /**
  1619. * Creates a new sequence
  1620. *
  1621. * The name of a given sequence is determined by passing the string
  1622. * provided in the <var>$seq_name</var> argument through PHP's sprintf()
  1623. * function using the value from the <var>seqname_format</var> option as
  1624. * the sprintf()'s format argument.
  1625. *
  1626. * <var>seqname_format</var> is set via setOption().
  1627. *
  1628. * @param string $seq_name name of the new sequence
  1629. *
  1630. * @return int DB_OK on success. A DB_Error object on failure.
  1631. *
  1632. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  1633. * DB_common::nextID()
  1634. */
  1635. function createSequence($seq_name)
  1636. {
  1637. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1638. }
  1639. // }}}
  1640. // {{{ dropSequence()
  1641. /**
  1642. * Deletes a sequence
  1643. *
  1644. * @param string $seq_name name of the sequence to be deleted
  1645. *
  1646. * @return int DB_OK on success. A DB_Error object on failure.
  1647. *
  1648. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  1649. * DB_common::nextID()
  1650. */
  1651. function dropSequence($seq_name)
  1652. {
  1653. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1654. }
  1655. // }}}
  1656. // {{{ raiseError()
  1657. /**
  1658. * Communicates an error and invoke error callbacks, etc
  1659. *
  1660. * Basically a wrapper for PEAR::raiseError without the message string.
  1661. *
  1662. * @param mixed integer error code, or a PEAR error object (all
  1663. * other parameters are ignored if this parameter is
  1664. * an object
  1665. * @param int error mode, see PEAR_Error docs
  1666. * @param mixed if error mode is PEAR_ERROR_TRIGGER, this is the
  1667. * error level (E_USER_NOTICE etc). If error mode is
  1668. * PEAR_ERROR_CALLBACK, this is the callback function,
  1669. * either as a function name, or as an array of an
  1670. * object and method name. For other error modes this
  1671. * parameter is ignored.
  1672. * @param string extra debug information. Defaults to the last
  1673. * query and native error code.
  1674. * @param mixed native error code, integer or string depending the
  1675. * backend
  1676. *
  1677. * @return object the PEAR_Error object
  1678. *
  1679. * @see PEAR_Error
  1680. */
  1681. function &raiseError($code = DB_ERROR, $mode = null, $options = null,
  1682. $userinfo = null, $nativecode = null)
  1683. {
  1684. // The error is yet a DB error object
  1685. if (is_object($code)) {
  1686. // because we the static PEAR::raiseError, our global
  1687. // handler should be used if it is set
  1688. if ($mode === null && !empty($this->_default_error_mode)) {
  1689. $mode = $this->_default_error_mode;
  1690. $options = $this->_default_error_options;
  1691. }
  1692. $tmp = PEAR::raiseError($code, null, $mode, $options,
  1693. null, null, true);
  1694. return $tmp;
  1695. }
  1696. if ($userinfo === null) {
  1697. $userinfo = $this->last_query;
  1698. }
  1699. if ($nativecode) {
  1700. $userinfo .= ' [nativecode=' . trim($nativecode) . ']';
  1701. } else {
  1702. $userinfo .= ' [DB Error: ' . DB::errorMessage($code) . ']';
  1703. }
  1704. $tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo,
  1705. 'DB_Error', true);
  1706. return $tmp;
  1707. }
  1708. // }}}
  1709. // {{{ errorNative()
  1710. /**
  1711. * Gets the DBMS' native error code produced by the last query
  1712. *
  1713. * @return mixed the DBMS' error code. A DB_Error object on failure.
  1714. */
  1715. function errorNative()
  1716. {
  1717. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1718. }
  1719. // }}}
  1720. // {{{ errorCode()
  1721. /**
  1722. * Maps native error codes to DB's portable ones
  1723. *
  1724. * Uses the <var>$errorcode_map</var> property defined in each driver.
  1725. *
  1726. * @param string|int $nativecode the error code returned by the DBMS
  1727. *
  1728. * @return int the portable DB error code. Return DB_ERROR if the
  1729. * current driver doesn't have a mapping for the
  1730. * $nativecode submitted.
  1731. */
  1732. function errorCode($nativecode)
  1733. {
  1734. if (isset($this->errorcode_map[$nativecode])) {
  1735. return $this->errorcode_map[$nativecode];
  1736. }
  1737. // Fall back to DB_ERROR if there was no mapping.
  1738. return DB_ERROR;
  1739. }
  1740. // }}}
  1741. // {{{ errorMessage()
  1742. /**
  1743. * Maps a DB error code to a textual message
  1744. *
  1745. * @param integer $dbcode the DB error code
  1746. *
  1747. * @return string the error message corresponding to the error code
  1748. * submitted. FALSE if the error code is unknown.
  1749. *
  1750. * @see DB::errorMessage()
  1751. */
  1752. function errorMessage($dbcode)
  1753. {
  1754. return DB::errorMessage($this->errorcode_map[$dbcode]);
  1755. }
  1756. // }}}
  1757. // {{{ tableInfo()
  1758. /**
  1759. * Returns information about a table or a result set
  1760. *
  1761. * The format of the resulting array depends on which <var>$mode</var>
  1762. * you select. The sample output below is based on this query:
  1763. * <pre>
  1764. * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
  1765. * FROM tblFoo
  1766. * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
  1767. * </pre>
  1768. *
  1769. * <ul>
  1770. * <li>
  1771. *
  1772. * <kbd>null</kbd> (default)
  1773. * <pre>
  1774. * [0] => Array (
  1775. * [table] => tblFoo
  1776. * [name] => fldId
  1777. * [type] => int
  1778. * [len] => 11
  1779. * [flags] => primary_key not_null
  1780. * )
  1781. * [1] => Array (
  1782. * [table] => tblFoo
  1783. * [name] => fldPhone
  1784. * [type] => string
  1785. * [len] => 20
  1786. * [flags] =>
  1787. * )
  1788. * [2] => Array (
  1789. * [table] => tblBar
  1790. * [name] => fldId
  1791. * [type] => int
  1792. * [len] => 11
  1793. * [flags] => primary_key not_null
  1794. * )
  1795. * </pre>
  1796. *
  1797. * </li><li>
  1798. *
  1799. * <kbd>DB_TABLEINFO_ORDER</kbd>
  1800. *
  1801. * <p>In addition to the information found in the default output,
  1802. * a notation of the number of columns is provided by the
  1803. * <samp>num_fields</samp> element while the <samp>order</samp>
  1804. * element provides an array with the column names as the keys and
  1805. * their location index number (corresponding to the keys in the
  1806. * the default output) as the values.</p>
  1807. *
  1808. * <p>If a result set has identical field names, the last one is
  1809. * used.</p>
  1810. *
  1811. * <pre>
  1812. * [num_fields] => 3
  1813. * [order] => Array (
  1814. * [fldId] => 2
  1815. * [fldTrans] => 1
  1816. * )
  1817. * </pre>
  1818. *
  1819. * </li><li>
  1820. *
  1821. * <kbd>DB_TABLEINFO_ORDERTABLE</kbd>
  1822. *
  1823. * <p>Similar to <kbd>DB_TABLEINFO_ORDER</kbd> but adds more
  1824. * dimensions to the array in which the table names are keys and
  1825. * the field names are sub-keys. This is helpful for queries that
  1826. * join tables which have identical field names.</p>
  1827. *
  1828. * <pre>
  1829. * [num_fields] => 3
  1830. * [ordertable] => Array (
  1831. * [tblFoo] => Array (
  1832. * [fldId] => 0
  1833. * [fldPhone] => 1
  1834. * )
  1835. * [tblBar] => Array (
  1836. * [fldId] => 2
  1837. * )
  1838. * )
  1839. * </pre>
  1840. *
  1841. * </li>
  1842. * </ul>
  1843. *
  1844. * The <samp>flags</samp> element contains a space separated list
  1845. * of extra information about the field. This data is inconsistent
  1846. * between DBMS's due to the way each DBMS works.
  1847. * + <samp>primary_key</samp>
  1848. * + <samp>unique_key</samp>
  1849. * + <samp>multiple_key</samp>
  1850. * + <samp>not_null</samp>
  1851. *
  1852. * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
  1853. * elements if <var>$result</var> is a table name. The following DBMS's
  1854. * provide full information from queries:
  1855. * + fbsql
  1856. * + mysql
  1857. *
  1858. * If the 'portability' option has <samp>DB_PORTABILITY_LOWERCASE</samp>
  1859. * turned on, the names of tables and fields will be lowercased.
  1860. *
  1861. * @param object|string $result DB_result object from a query or a
  1862. * string containing the name of a table.
  1863. * While this also accepts a query result
  1864. * resource identifier, this behavior is
  1865. * deprecated.
  1866. * @param int $mode either unused or one of the tableInfo modes:
  1867. * <kbd>DB_TABLEINFO_ORDERTABLE</kbd>,
  1868. * <kbd>DB_TABLEINFO_ORDER</kbd> or
  1869. * <kbd>DB_TABLEINFO_FULL</kbd> (which does both).
  1870. * These are bitwise, so the first two can be
  1871. * combined using <kbd>|</kbd>.
  1872. *
  1873. * @return array an associative array with the information requested.
  1874. * A DB_Error object on failure.
  1875. *
  1876. * @see DB_common::setOption()
  1877. */
  1878. function tableInfo($result, $mode = null)
  1879. {
  1880. /*
  1881. * If the DB_<driver> class has a tableInfo() method, that one
  1882. * overrides this one. But, if the driver doesn't have one,
  1883. * this method runs and tells users about that fact.
  1884. */
  1885. return $this->raiseError(DB_ERROR_NOT_CAPABLE);
  1886. }
  1887. // }}}
  1888. // {{{ getTables()
  1889. /**
  1890. * Lists the tables in the current database
  1891. *
  1892. * @return array the list of tables. A DB_Error object on failure.
  1893. *
  1894. * @deprecated Method deprecated some time before Release 1.2
  1895. */
  1896. function getTables()
  1897. {
  1898. return $this->getListOf('tables');
  1899. }
  1900. // }}}
  1901. // {{{ getListOf()
  1902. /**
  1903. * Lists internal database information
  1904. *
  1905. * @param string $type type of information being sought.
  1906. * Common items being sought are:
  1907. * tables, databases, users, views, functions
  1908. * Each DBMS's has its own capabilities.
  1909. *
  1910. * @return array an array listing the items sought.
  1911. * A DB DB_Error object on failure.
  1912. */
  1913. function getListOf($type)
  1914. {
  1915. $sql = $this->getSpecialQuery($type);
  1916. if ($sql === null) {
  1917. $this->last_query = '';
  1918. return $this->raiseError(DB_ERROR_UNSUPPORTED);
  1919. } elseif (is_int($sql) || DB::isError($sql)) {
  1920. // Previous error
  1921. return $this->raiseError($sql);
  1922. } elseif (is_array($sql)) {
  1923. // Already the result
  1924. return $sql;
  1925. }
  1926. // Launch this query
  1927. return $this->getCol($sql);
  1928. }
  1929. // }}}
  1930. // {{{ getSpecialQuery()
  1931. /**
  1932. * Obtains the query string needed for listing a given type of objects
  1933. *
  1934. * @param string $type the kind of objects you want to retrieve
  1935. *
  1936. * @return string the SQL query string or null if the driver doesn't
  1937. * support the object type requested
  1938. *
  1939. * @access protected
  1940. * @see DB_common::getListOf()
  1941. */
  1942. function getSpecialQuery($type)
  1943. {
  1944. return $this->raiseError(DB_ERROR_UNSUPPORTED);
  1945. }
  1946. // }}}
  1947. // {{{ _rtrimArrayValues()
  1948. /**
  1949. * Right-trims all strings in an array
  1950. *
  1951. * @param array $array the array to be trimmed (passed by reference)
  1952. *
  1953. * @return void
  1954. *
  1955. * @access protected
  1956. */
  1957. function _rtrimArrayValues(&$array)
  1958. {
  1959. foreach ($array as $key => $value) {
  1960. if (is_string($value)) {
  1961. $array[$key] = rtrim($value);
  1962. }
  1963. }
  1964. }
  1965. // }}}
  1966. // {{{ _convertNullArrayValuesToEmpty()
  1967. /**
  1968. * Converts all null values in an array to empty strings
  1969. *
  1970. * @param array $array the array to be de-nullified (passed by reference)
  1971. *
  1972. * @return void
  1973. *
  1974. * @access protected
  1975. */
  1976. function _convertNullArrayValuesToEmpty(&$array)
  1977. {
  1978. foreach ($array as $key => $value) {
  1979. if (is_null($value)) {
  1980. $array[$key] = '';
  1981. }
  1982. }
  1983. }
  1984. // }}}
  1985. }
  1986. /*
  1987. * Local variables:
  1988. * tab-width: 4
  1989. * c-basic-offset: 4
  1990. * End:
  1991. */
  1992. ?>