2 // vim: set et ts=4 sw=4 fdm=marker:
3 // +----------------------------------------------------------------------+
4 // | PHP versions 4 and 5 |
5 // +----------------------------------------------------------------------+
6 // | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
7 // | Stig. S. Bakken, Lukas Smith |
8 // | All rights reserved. |
9 // +----------------------------------------------------------------------+
10 // | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
11 // | API as well as database abstraction for PHP applications. |
12 // | This LICENSE is in the BSD license style. |
14 // | Redistribution and use in source and binary forms, with or without |
15 // | modification, are permitted provided that the following conditions |
18 // | Redistributions of source code must retain the above copyright |
19 // | notice, this list of conditions and the following disclaimer. |
21 // | Redistributions in binary form must reproduce the above copyright |
22 // | notice, this list of conditions and the following disclaimer in the |
23 // | documentation and/or other materials provided with the distribution. |
25 // | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
26 // | Lukas Smith nor the names of his contributors may be used to endorse |
27 // | or promote products derived from this software without specific prior|
28 // | written permission. |
30 // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
31 // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
32 // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
33 // | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
34 // | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
35 // | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
36 // | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
37 // | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
38 // | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
39 // | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
40 // | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
41 // | POSSIBILITY OF SUCH DAMAGE. |
42 // +----------------------------------------------------------------------+
43 // | Author: Lukas Smith <smith@pooteeweet.org> |
44 // +----------------------------------------------------------------------+
46 // $Id: mysqli.php 327320 2012-08-27 15:52:50Z danielc $
54 * @author Lukas Smith <smith@pooteeweet.org>
56 class MDB2_Driver_mysqli extends MDB2_Driver_Common
60 public $string_quoting = array(
64 'escape_pattern' => '\\',
67 public $identifier_quoting = array(
74 * The ouptut of mysqli_errno() in _doQuery(), if any.
77 protected $_query_errno;
80 * The ouptut of mysqli_error() in _doQuery(), if any.
83 protected $_query_error;
85 public $sql_comments = array(
86 array('start' => '-- ', 'end' => "\n", 'escape' => false),
87 array('start' => '#', 'end' => "\n", 'escape' => false),
88 array('start' => '/*', 'end' => '*/', 'escape' => false),
91 protected $server_capabilities_checked = false;
93 protected $start_transaction = false;
95 public $varchar_max_length = 255;
103 function __construct()
105 parent::__construct();
107 $this->phptype = 'mysqli';
108 $this->dbsyntax = 'mysql';
110 $this->supported['sequences'] = 'emulated';
111 $this->supported['indexes'] = true;
112 $this->supported['affected_rows'] = true;
113 $this->supported['transactions'] = false;
114 $this->supported['savepoints'] = false;
115 $this->supported['summary_functions'] = true;
116 $this->supported['order_by_text'] = true;
117 $this->supported['current_id'] = 'emulated';
118 $this->supported['limit_queries'] = true;
119 $this->supported['LOBs'] = true;
120 $this->supported['replace'] = true;
121 $this->supported['sub_selects'] = 'emulated';
122 $this->supported['triggers'] = false;
123 $this->supported['auto_increment'] = true;
124 $this->supported['primary_key'] = true;
125 $this->supported['result_introspection'] = true;
126 $this->supported['prepared_statements'] = 'emulated';
127 $this->supported['identifier_quoting'] = true;
128 $this->supported['pattern_escaping'] = true;
129 $this->supported['new_link'] = true;
131 $this->options['DBA_username'] = false;
132 $this->options['DBA_password'] = false;
133 $this->options['default_table_type'] = '';
134 $this->options['multi_query'] = false;
135 $this->options['max_identifiers_length'] = 64;
137 $this->_reCheckSupportedOptions();
141 // {{{ _reCheckSupportedOptions()
144 * If the user changes certain options, other capabilities may depend
145 * on the new settings, so we need to check them (again).
149 function _reCheckSupportedOptions()
151 $this->supported['transactions'] = $this->options['use_transactions'];
152 $this->supported['savepoints'] = $this->options['use_transactions'];
153 if ($this->options['default_table_type']) {
154 switch (strtoupper($this->options['default_table_type'])) {
166 $this->supported['savepoints'] = false;
167 $this->supported['transactions'] = false;
168 $this->warnings[] = $this->options['default_table_type'] .
169 ' is not a supported default table type';
176 // {{{ function setOption($option, $value)
179 * set the option for the db class
181 * @param string option name
182 * @param mixed value for the option
184 * @return mixed MDB2_OK or MDB2 Error Object
188 function setOption($option, $value)
190 $res = parent::setOption($option, $value);
191 $this->_reCheckSupportedOptions();
198 * This method is used to collect information about an error
200 * @param integer $error
204 function errorInfo($error = null)
206 if ($this->_query_errno) {
207 $native_code = $this->_query_errno;
208 $native_msg = $this->_query_error;
209 } elseif ($this->connection) {
210 $native_code = @mysqli_errno($this->connection);
211 $native_msg = @mysqli_error($this->connection);
213 $native_code = @mysqli_connect_errno();
214 $native_msg = @mysqli_connect_error();
216 if (null === $error) {
218 if (empty($ecode_map)) {
220 1000 => MDB2_ERROR_INVALID, //hashchk
221 1001 => MDB2_ERROR_INVALID, //isamchk
222 1004 => MDB2_ERROR_CANNOT_CREATE,
223 1005 => MDB2_ERROR_CANNOT_CREATE,
224 1006 => MDB2_ERROR_CANNOT_CREATE,
225 1007 => MDB2_ERROR_ALREADY_EXISTS,
226 1008 => MDB2_ERROR_CANNOT_DROP,
227 1009 => MDB2_ERROR_CANNOT_DROP,
228 1010 => MDB2_ERROR_CANNOT_DROP,
229 1011 => MDB2_ERROR_CANNOT_DELETE,
230 1022 => MDB2_ERROR_ALREADY_EXISTS,
231 1029 => MDB2_ERROR_NOT_FOUND,
232 1032 => MDB2_ERROR_NOT_FOUND,
233 1044 => MDB2_ERROR_ACCESS_VIOLATION,
234 1045 => MDB2_ERROR_ACCESS_VIOLATION,
235 1046 => MDB2_ERROR_NODBSELECTED,
236 1048 => MDB2_ERROR_CONSTRAINT,
237 1049 => MDB2_ERROR_NOSUCHDB,
238 1050 => MDB2_ERROR_ALREADY_EXISTS,
239 1051 => MDB2_ERROR_NOSUCHTABLE,
240 1054 => MDB2_ERROR_NOSUCHFIELD,
241 1060 => MDB2_ERROR_ALREADY_EXISTS,
242 1061 => MDB2_ERROR_ALREADY_EXISTS,
243 1062 => MDB2_ERROR_ALREADY_EXISTS,
244 1064 => MDB2_ERROR_SYNTAX,
245 1067 => MDB2_ERROR_INVALID,
246 1072 => MDB2_ERROR_NOT_FOUND,
247 1086 => MDB2_ERROR_ALREADY_EXISTS,
248 1091 => MDB2_ERROR_NOT_FOUND,
249 1100 => MDB2_ERROR_NOT_LOCKED,
250 1109 => MDB2_ERROR_NOT_FOUND,
251 1125 => MDB2_ERROR_ALREADY_EXISTS,
252 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
253 1138 => MDB2_ERROR_INVALID,
254 1142 => MDB2_ERROR_ACCESS_VIOLATION,
255 1143 => MDB2_ERROR_ACCESS_VIOLATION,
256 1146 => MDB2_ERROR_NOSUCHTABLE,
257 1149 => MDB2_ERROR_SYNTAX,
258 1169 => MDB2_ERROR_CONSTRAINT,
259 1176 => MDB2_ERROR_NOT_FOUND,
260 1177 => MDB2_ERROR_NOSUCHTABLE,
261 1213 => MDB2_ERROR_DEADLOCK,
262 1216 => MDB2_ERROR_CONSTRAINT,
263 1217 => MDB2_ERROR_CONSTRAINT,
264 1227 => MDB2_ERROR_ACCESS_VIOLATION,
265 1235 => MDB2_ERROR_CANNOT_CREATE,
266 1299 => MDB2_ERROR_INVALID_DATE,
267 1300 => MDB2_ERROR_INVALID,
268 1304 => MDB2_ERROR_ALREADY_EXISTS,
269 1305 => MDB2_ERROR_NOT_FOUND,
270 1306 => MDB2_ERROR_CANNOT_DROP,
271 1307 => MDB2_ERROR_CANNOT_CREATE,
272 1334 => MDB2_ERROR_CANNOT_ALTER,
273 1339 => MDB2_ERROR_NOT_FOUND,
274 1356 => MDB2_ERROR_INVALID,
275 1359 => MDB2_ERROR_ALREADY_EXISTS,
276 1360 => MDB2_ERROR_NOT_FOUND,
277 1363 => MDB2_ERROR_NOT_FOUND,
278 1365 => MDB2_ERROR_DIVZERO,
279 1451 => MDB2_ERROR_CONSTRAINT,
280 1452 => MDB2_ERROR_CONSTRAINT,
281 1542 => MDB2_ERROR_CANNOT_DROP,
282 1546 => MDB2_ERROR_CONSTRAINT,
283 1582 => MDB2_ERROR_CONSTRAINT,
284 2003 => MDB2_ERROR_CONNECT_FAILED,
285 2019 => MDB2_ERROR_INVALID,
288 if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
289 $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
290 $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
291 $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
293 // Doing this in case mode changes during runtime.
294 $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
295 $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
296 $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
298 if (isset($ecode_map[$native_code])) {
299 $error = $ecode_map[$native_code];
302 return array($error, $native_code, $native_msg);
309 * Quotes a string so it can be safely used in a query. It will quote
310 * the text so it can safely be used within a query.
312 * @param string the input string to quote
313 * @param bool escape wildcards
315 * @return string quoted string
319 function escape($text, $escape_wildcards = false)
321 if ($escape_wildcards) {
322 $text = $this->escapePattern($text);
324 $connection = $this->getConnection();
325 if (MDB2::isError($connection)) {
328 $text = @mysqli_real_escape_string($connection, $text);
333 // {{{ beginTransaction()
336 * Start a transaction or set a savepoint.
338 * @param string name of a savepoint to set
339 * @return mixed MDB2_OK on success, a MDB2 error on failure
343 function beginTransaction($savepoint = null)
345 $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
346 $this->_getServerCapabilities();
347 if (null !== $savepoint) {
348 if (!$this->supports('savepoints')) {
349 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
350 'savepoints are not supported', __FUNCTION__);
352 if (!$this->in_transaction) {
353 return $this->raiseError(MDB2_ERROR_INVALID, null, null,
354 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
356 $query = 'SAVEPOINT '.$savepoint;
357 return $this->_doQuery($query, true);
359 if ($this->in_transaction) {
360 return MDB2_OK; //nothing to do
362 $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
363 $result = $this->_doQuery($query, true);
364 if (MDB2::isError($result)) {
367 $this->in_transaction = true;
375 * Commit the database changes done during a transaction that is in
376 * progress or release a savepoint. This function may only be called when
377 * auto-committing is disabled, otherwise it will fail. Therefore, a new
378 * transaction is implicitly started after committing the pending changes.
380 * @param string name of a savepoint to release
381 * @return mixed MDB2_OK on success, a MDB2 error on failure
385 function commit($savepoint = null)
387 $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
388 if (!$this->in_transaction) {
389 return $this->raiseError(MDB2_ERROR_INVALID, null, null,
390 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
392 if (null !== $savepoint) {
393 if (!$this->supports('savepoints')) {
394 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
395 'savepoints are not supported', __FUNCTION__);
397 $server_info = $this->getServerVersion();
398 if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
401 $query = 'RELEASE SAVEPOINT '.$savepoint;
402 return $this->_doQuery($query, true);
405 if (!$this->supports('transactions')) {
406 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
407 'transactions are not supported', __FUNCTION__);
410 $result = $this->_doQuery('COMMIT', true);
411 if (MDB2::isError($result)) {
414 if (!$this->start_transaction) {
415 $query = 'SET AUTOCOMMIT = 1';
416 $result = $this->_doQuery($query, true);
417 if (MDB2::isError($result)) {
421 $this->in_transaction = false;
429 * Cancel any database changes done during a transaction or since a specific
430 * savepoint that is in progress. This function may only be called when
431 * auto-committing is disabled, otherwise it will fail. Therefore, a new
432 * transaction is implicitly started after canceling the pending changes.
434 * @param string name of a savepoint to rollback to
435 * @return mixed MDB2_OK on success, a MDB2 error on failure
439 function rollback($savepoint = null)
441 $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
442 if (!$this->in_transaction) {
443 return $this->raiseError(MDB2_ERROR_INVALID, null, null,
444 'rollback cannot be done changes are auto committed', __FUNCTION__);
446 if (null !== $savepoint) {
447 if (!$this->supports('savepoints')) {
448 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
449 'savepoints are not supported', __FUNCTION__);
451 $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
452 return $this->_doQuery($query, true);
456 $result = $this->_doQuery($query, true);
457 if (MDB2::isError($result)) {
460 if (!$this->start_transaction) {
461 $query = 'SET AUTOCOMMIT = 1';
462 $result = $this->_doQuery($query, true);
463 if (MDB2::isError($result)) {
467 $this->in_transaction = false;
472 // {{{ function setTransactionIsolation()
475 * Set the transacton isolation level.
477 * @param string standard isolation level
478 * READ UNCOMMITTED (allows dirty reads)
479 * READ COMMITTED (prevents dirty reads)
480 * REPEATABLE READ (prevents nonrepeatable reads)
481 * SERIALIZABLE (prevents phantom reads)
482 * @param array some transaction options:
483 * 'wait' => 'WAIT' | 'NO WAIT'
484 * 'rw' => 'READ WRITE' | 'READ ONLY'
486 * @return mixed MDB2_OK on success, a MDB2 error on failure
491 function setTransactionIsolation($isolation, $options = array())
493 $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
494 if (!$this->supports('transactions')) {
495 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
496 'transactions are not supported', __FUNCTION__);
498 switch ($isolation) {
499 case 'READ UNCOMMITTED':
500 case 'READ COMMITTED':
501 case 'REPEATABLE READ':
505 return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
506 'isolation level is not supported: '.$isolation, __FUNCTION__);
509 $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
510 return $this->_doQuery($query, true);
517 * do the grunt work of the connect
519 * @return connection on success or MDB2 Error Object on failure
522 function _doConnect($username, $password, $persistent = false)
524 if (!extension_loaded($this->phptype)) {
525 return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
526 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
529 $connection = @mysqli_init();
530 if (!empty($this->dsn['charset']) && defined('MYSQLI_SET_CHARSET_NAME')) {
531 @mysqli_options($connection, MYSQLI_SET_CHARSET_NAME, $this->dsn['charset']);
534 if ($this->options['ssl']) {
537 empty($this->dsn['key']) ? null : $this->dsn['key'],
538 empty($this->dsn['cert']) ? null : $this->dsn['cert'],
539 empty($this->dsn['ca']) ? null : $this->dsn['ca'],
540 empty($this->dsn['capath']) ? null : $this->dsn['capath'],
541 empty($this->dsn['cipher']) ? null : $this->dsn['cipher']
545 if (!@mysqli_real_connect(
547 $this->dsn['hostspec'],
550 $this->database_name,
554 if (($err = @mysqli_connect_error()) != '') {
555 return $this->raiseError(null,
556 null, null, $err, __FUNCTION__);
558 return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
559 'unable to establish a connection', __FUNCTION__);
563 if (!empty($this->dsn['charset']) && !defined('MYSQLI_SET_CHARSET_NAME')) {
564 $result = $this->setCharset($this->dsn['charset'], $connection);
565 if (MDB2::isError($result)) {
577 * Connect to the database
579 * @return true on success, MDB2 Error Object on failure
583 if (is_object($this->connection)) {
584 //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0) {
585 if (MDB2::areEquals($this->connected_dsn, $this->dsn)) {
588 $this->connection = 0;
591 $connection = $this->_doConnect(
592 $this->dsn['username'],
593 $this->dsn['password']
595 if (MDB2::isError($connection)) {
599 $this->connection = $connection;
600 $this->connected_dsn = $this->dsn;
601 $this->connected_database_name = $this->database_name;
602 $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
604 $this->_getServerCapabilities();
613 * Set the charset on the current connection
615 * @param string charset (or array(charset, collation))
616 * @param resource connection handle
618 * @return true on success, MDB2 Error Object on failure
620 function setCharset($charset, $connection = null)
622 if (null === $connection) {
623 $connection = $this->getConnection();
624 if (MDB2::isError($connection)) {
629 if (is_array($charset) && 2 == count($charset)) {
630 $collation = array_pop($charset);
631 $charset = array_pop($charset);
633 $client_info = mysqli_get_client_version();
634 if (OS_WINDOWS && ((40111 > $client_info) ||
635 ((50000 <= $client_info) && (50006 > $client_info)))
637 $query = "SET NAMES '".mysqli_real_escape_string($connection, $charset)."'";
638 if (null !== $collation) {
639 $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
641 return $this->_doQuery($query, true, $connection);
643 if (!$result = mysqli_set_charset($connection, $charset)) {
644 $err = $this->raiseError(null, null, null,
645 'Could not set client character set', __FUNCTION__);
652 // {{{ databaseExists()
655 * check if given database name is exists?
657 * @param string $name name of the database that should be checked
659 * @return mixed true/false on success, a MDB2 error on failure
662 function databaseExists($name)
664 $connection = $this->_doConnect($this->dsn['username'],
665 $this->dsn['password']);
666 if (MDB2::isError($connection)) {
670 $result = @mysqli_select_db($connection, $name);
671 @mysqli_close($connection);
680 * Log out and disconnect from the database.
682 * @param boolean $force if the disconnect should be forced even if the
683 * connection is opened persistently
684 * @return mixed true on success, false if not connected and error
688 function disconnect($force = true)
690 if (is_object($this->connection)) {
691 if ($this->in_transaction) {
693 $database_name = $this->database_name;
694 $persistent = $this->options['persistent'];
695 $this->dsn = $this->connected_dsn;
696 $this->database_name = $this->connected_database_name;
697 $this->options['persistent'] = $this->opened_persistent;
700 $this->database_name = $database_name;
701 $this->options['persistent'] = $persistent;
705 $ok = @mysqli_close($this->connection);
707 return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
708 null, null, null, __FUNCTION__);
714 return parent::disconnect($force);
718 // {{{ standaloneQuery()
721 * execute a query as DBA
723 * @param string $query the SQL query
724 * @param mixed $types array that contains the types of the columns in
726 * @param boolean $is_manip if the query is a manipulation query
727 * @return mixed MDB2_OK on success, a MDB2 error on failure
730 function standaloneQuery($query, $types = null, $is_manip = false)
732 $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
733 $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
734 $connection = $this->_doConnect($user, $pass);
735 if (MDB2::isError($connection)) {
739 $offset = $this->offset;
740 $limit = $this->limit;
741 $this->offset = $this->limit = 0;
742 $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
744 $result = $this->_doQuery($query, $is_manip, $connection, $this->database_name);
745 if (!MDB2::isError($result)) {
746 $result = $this->_affectedRows($connection, $result);
749 @mysqli_close($connection);
758 * @param string $query query
759 * @param boolean $is_manip if the query is a manipulation query
760 * @param resource $connection
761 * @param string $database_name
762 * @return result or error object
765 function _doQuery($query, $is_manip = false, $connection = null, $database_name = null)
767 $this->last_query = $query;
768 $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
770 if (MDB2::isError($result)) {
775 if ($this->options['disable_query']) {
776 $result = $is_manip ? 0 : null;
780 if (null === $connection) {
781 $connection = $this->getConnection();
782 if (MDB2::isError($connection)) {
786 if (null === $database_name) {
787 $database_name = $this->database_name;
790 if ($database_name) {
791 if ($database_name != $this->connected_database_name) {
792 if (!@mysqli_select_db($connection, $database_name)) {
793 $err = $this->raiseError(null, null, null,
794 'Could not select the database: '.$database_name, __FUNCTION__);
797 $this->connected_database_name = $database_name;
801 if ($this->options['multi_query']) {
802 $result = mysqli_multi_query($connection, $query);
804 $resultmode = $this->options['result_buffering'] ? MYSQLI_USE_RESULT : MYSQLI_USE_RESULT;
805 $result = mysqli_query($connection, $query);
809 // Store now because standaloneQuery throws off $this->connection.
810 $this->_query_errno = mysqli_errno($connection);
811 if (0 !== $this->_query_errno) {
812 $this->_query_error = mysqli_error($connection);
813 $err = $this->raiseError(null, null, null,
814 'Could not execute statement', __FUNCTION__);
819 if ($this->options['multi_query']) {
820 if ($this->options['result_buffering']) {
821 if (!($result = @mysqli_store_result($connection))) {
822 $err = $this->raiseError(null, null, null,
823 'Could not get the first result from a multi query', __FUNCTION__);
826 } elseif (!($result = @mysqli_use_result($connection))) {
827 $err = $this->raiseError(null, null, null,
828 'Could not get the first result from a multi query', __FUNCTION__);
833 $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
838 // {{{ _affectedRows()
841 * Returns the number of rows affected
843 * @param resource $result
844 * @param resource $connection
845 * @return mixed MDB2 Error Object or the number of rows affected
848 function _affectedRows($connection, $result = null)
850 if (null === $connection) {
851 $connection = $this->getConnection();
852 if (MDB2::isError($connection)) {
856 return @mysqli_affected_rows($connection);
860 // {{{ _modifyQuery()
863 * Changes a query string for various DBMS specific reasons
865 * @param string $query query to modify
866 * @param boolean $is_manip if it is a DML query
867 * @param integer $limit limit the number of rows
868 * @param integer $offset start reading from given offset
869 * @return string modified query
872 function _modifyQuery($query, $is_manip, $limit, $offset)
874 if ($this->options['portability'] & MDB2_PORTABILITY_DELETE_COUNT) {
875 // "DELETE FROM table" gives 0 affected rows in MySQL.
876 // This little hack lets you know how many rows were deleted.
877 if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) {
878 $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/',
879 'DELETE FROM \1 WHERE 1=1', $query);
883 && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
885 $query = rtrim($query);
886 if (substr($query, -1) == ';') {
887 $query = substr($query, 0, -1);
890 // LIMIT doesn't always come last in the query
891 // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
893 if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
894 $after = $matches[0];
895 $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
896 } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
897 $after = $matches[0];
898 $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
899 } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
900 $after = $matches[0];
901 $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
905 return $query . " LIMIT $limit" . $after;
907 return $query . " LIMIT $offset, $limit" . $after;
914 // {{{ getServerVersion()
917 * return version information about the server
919 * @param bool $native determines if the raw version string should be returned
920 * @return mixed array/string with version information or MDB2 error object
923 function getServerVersion($native = false)
925 $connection = $this->getConnection();
926 if (MDB2::isError($connection)) {
929 if ($this->connected_server_info) {
930 $server_info = $this->connected_server_info;
932 $server_info = @mysqli_get_server_info($connection);
935 return $this->raiseError(null, null, null,
936 'Could not get server information', __FUNCTION__);
939 $this->connected_server_info = $server_info;
941 $tmp = explode('.', $server_info, 3);
942 if (isset($tmp[2]) && strpos($tmp[2], '-')) {
943 $tmp2 = explode('-', @$tmp[2], 2);
945 $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
948 $server_info = array(
949 'major' => isset($tmp[0]) ? $tmp[0] : null,
950 'minor' => isset($tmp[1]) ? $tmp[1] : null,
953 'native' => $server_info,
960 // {{{ _getServerCapabilities()
963 * Fetch some information about the server capabilities
964 * (transactions, subselects, prepared statements, etc).
968 function _getServerCapabilities()
970 if (!$this->server_capabilities_checked) {
971 $this->server_capabilities_checked = true;
974 $this->supported['sub_selects'] = 'emulated';
975 $this->supported['prepared_statements'] = 'emulated';
976 $this->supported['triggers'] = false;
977 $this->start_transaction = false;
978 $this->varchar_max_length = 255;
980 $server_info = $this->getServerVersion();
981 if (is_array($server_info)) {
982 $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
984 if (!version_compare($server_version, '4.1.0', '<')) {
985 $this->supported['sub_selects'] = true;
986 $this->supported['prepared_statements'] = true;
989 // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
990 if (version_compare($server_version, '4.1.0', '>=')) {
991 if (version_compare($server_version, '4.1.1', '<')) {
992 $this->supported['savepoints'] = false;
994 } elseif (version_compare($server_version, '4.0.14', '<')) {
995 $this->supported['savepoints'] = false;
998 if (!version_compare($server_version, '4.0.11', '<')) {
999 $this->start_transaction = true;
1002 if (!version_compare($server_version, '5.0.3', '<')) {
1003 $this->varchar_max_length = 65532;
1006 if (!version_compare($server_version, '5.0.2', '<')) {
1007 $this->supported['triggers'] = true;
1014 // {{{ function _skipUserDefinedVariable($query, $position)
1017 * Utility method, used by prepare() to avoid misinterpreting MySQL user
1018 * defined variables (SELECT @x:=5) for placeholders.
1019 * Check if the placeholder is a false positive, i.e. if it is an user defined
1020 * variable instead. If so, skip it and advance the position, otherwise
1021 * return the current position, which is valid
1023 * @param string $query
1024 * @param integer $position current string cursor position
1025 * @return integer $new_position
1028 function _skipUserDefinedVariable($query, $position)
1030 $found = strpos(strrev(substr($query, 0, $position)), '@');
1031 if (false === $found) {
1034 $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
1035 $substring = substr($query, $pos, $position - $pos + 2);
1036 if (preg_match('/^@\w+\s*:=$/', $substring)) {
1037 return $position + 1; //found an user defined variable: skip it
1046 * Prepares a query for multiple execution with execute().
1047 * With some database backends, this is emulated.
1048 * prepare() requires a generic query as string like
1049 * 'INSERT INTO numbers VALUES(?,?)' or
1050 * 'INSERT INTO numbers VALUES(:foo,:bar)'.
1051 * The ? and :name and are placeholders which can be set using
1052 * bindParam() and the query can be sent off using the execute() method.
1053 * The allowed format for :name can be set with the 'bindname_format' option.
1055 * @param string $query the query to prepare
1056 * @param mixed $types array that contains the types of the placeholders
1057 * @param mixed $result_types array that contains the types of the columns in
1058 * the result set or MDB2_PREPARE_RESULT, if set to
1059 * MDB2_PREPARE_MANIP the query is handled as a manipulation query
1060 * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
1061 * @return mixed resource handle for the prepared query on success, a MDB2
1064 * @see bindParam, execute
1066 function prepare($query, $types = null, $result_types = null, $lobs = array())
1068 // connect to get server capabilities (http://pear.php.net/bugs/16147)
1069 $connection = $this->getConnection();
1070 if (MDB2::isError($connection)) {
1074 if ($this->options['emulate_prepared']
1075 || $this->supported['prepared_statements'] !== true
1077 return parent::prepare($query, $types, $result_types, $lobs);
1079 $is_manip = ($result_types === MDB2_PREPARE_MANIP);
1080 $offset = $this->offset;
1081 $limit = $this->limit;
1082 $this->offset = $this->limit = 0;
1083 $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
1084 $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
1086 if (MDB2::isError($result)) {
1091 $placeholder_type_guess = $placeholder_type = null;
1094 $positions = array();
1096 while ($position < strlen($query)) {
1097 $q_position = strpos($query, $question, $position);
1098 $c_position = strpos($query, $colon, $position);
1099 if ($q_position && $c_position) {
1100 $p_position = min($q_position, $c_position);
1101 } elseif ($q_position) {
1102 $p_position = $q_position;
1103 } elseif ($c_position) {
1104 $p_position = $c_position;
1108 if (null === $placeholder_type) {
1109 $placeholder_type_guess = $query[$p_position];
1112 $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
1113 if (MDB2::isError($new_pos)) {
1116 if ($new_pos != $position) {
1117 $position = $new_pos;
1118 continue; //evaluate again starting from the new position
1121 //make sure this is not part of an user defined variable
1122 $new_pos = $this->_skipUserDefinedVariable($query, $position);
1123 if ($new_pos != $position) {
1124 $position = $new_pos;
1125 continue; //evaluate again starting from the new position
1128 if ($query[$position] == $placeholder_type_guess) {
1129 if (null === $placeholder_type) {
1130 $placeholder_type = $query[$p_position];
1131 $question = $colon = $placeholder_type;
1133 if ($placeholder_type == ':') {
1134 $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
1135 $parameter = preg_replace($regexp, '\\1', $query);
1136 if ($parameter === '') {
1137 $err = $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
1138 'named parameter name must match "bindname_format" option', __FUNCTION__);
1141 $positions[$p_position] = $parameter;
1142 $query = substr_replace($query, '?', $position, strlen($parameter)+1);
1144 $positions[$p_position] = count($positions);
1146 $position = $p_position + 1;
1148 $position = $p_position;
1153 static $prep_statement_counter = 1;
1154 $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
1155 $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
1156 $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
1158 $statement = $this->_doQuery($query, true, $connection);
1159 if (MDB2::isError($statement)) {
1162 $statement = $statement_name;
1164 $statement = @mysqli_prepare($connection, $query);
1166 $err = $this->raiseError(null, null, null,
1167 'Unable to create prepared statement handle', __FUNCTION__);
1172 $class_name = 'MDB2_Statement_'.$this->phptype;
1173 $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
1174 $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
1182 * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
1183 * query, except that if there is already a row in the table with the same
1184 * key field values, the old row is deleted before the new row is inserted.
1186 * The REPLACE type of query does not make part of the SQL standards. Since
1187 * practically only MySQL implements it natively, this type of query is
1188 * emulated through this method for other DBMS using standard types of
1189 * queries inside a transaction to assure the atomicity of the operation.
1193 * @param string $table name of the table on which the REPLACE query will
1195 * @param array $fields associative array that describes the fields and the
1196 * values that will be inserted or updated in the specified table. The
1197 * indexes of the array are the names of all the fields of the table. The
1198 * values of the array are also associative arrays that describe the
1199 * values and other properties of the table fields.
1201 * Here follows a list of field properties that need to be specified:
1204 * Value to be assigned to the specified field. This value may be
1205 * of specified in database independent type format as this
1206 * function can perform the necessary datatype conversions.
1209 * this property is required unless the Null property
1213 * Name of the type of the field. Currently, all types Metabase
1214 * are supported except for clob and blob.
1216 * Default: no type conversion
1219 * Boolean property that indicates that the value for this field
1220 * should be set to null.
1222 * The default value for fields missing in INSERT queries may be
1223 * specified the definition of a table. Often, the default value
1224 * is already null, but since the REPLACE may be emulated using
1225 * an UPDATE query, make sure that all fields of the table are
1226 * listed in this function argument array.
1231 * Boolean property that indicates that this field should be
1232 * handled as a primary key or at least as part of the compound
1233 * unique index of the table that will determine the row that will
1234 * updated if it exists or inserted a new row otherwise.
1236 * This function will fail if no key field is specified or if the
1237 * value of a key field is set to null because fields that are
1238 * part of unique index they may not be null.
1242 * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
1243 * @return mixed MDB2_OK on success, a MDB2 error on failure
1245 function replace($table, $fields)
1247 $count = count($fields);
1248 $query = $values = '';
1249 $keys = $colnum = 0;
1250 for (reset($fields); $colnum < $count; next($fields), $colnum++) {
1251 $name = key($fields);
1256 $query.= $this->quoteIdentifier($name, true);
1257 if (isset($fields[$name]['null']) && $fields[$name]['null']) {
1260 $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
1261 $value = $this->quote($fields[$name]['value'], $type);
1262 if (MDB2::isError($value)) {
1267 if (isset($fields[$name]['key']) && $fields[$name]['key']) {
1268 if ($value === 'NULL') {
1269 return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
1270 'key value '.$name.' may not be NULL', __FUNCTION__);
1276 return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
1277 'not specified which fields are keys', __FUNCTION__);
1280 $connection = $this->getConnection();
1281 if (MDB2::isError($connection)) {
1285 $table = $this->quoteIdentifier($table, true);
1286 $query = "REPLACE INTO $table ($query) VALUES ($values)";
1287 $result = $this->_doQuery($query, true, $connection);
1288 if (MDB2::isError($result)) {
1291 return $this->_affectedRows($connection, $result);
1298 * Returns the next free id of a sequence
1300 * @param string $seq_name name of the sequence
1301 * @param boolean $ondemand when true the sequence is
1302 * automatic created, if it
1305 * @return mixed MDB2 Error Object or id
1308 function nextID($seq_name, $ondemand = true)
1310 $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
1311 $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
1312 $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
1313 $this->pushErrorHandling(PEAR_ERROR_RETURN);
1314 $this->expectError(MDB2_ERROR_NOSUCHTABLE);
1315 $result = $this->_doQuery($query, true);
1317 $this->popErrorHandling();
1318 if (MDB2::isError($result)) {
1319 if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
1320 $this->loadModule('Manager', null, true);
1321 $result = $this->manager->createSequence($seq_name);
1322 if (MDB2::isError($result)) {
1323 return $this->raiseError($result, null, null,
1324 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
1326 return $this->nextID($seq_name, false);
1331 $value = $this->lastInsertID();
1332 if (is_numeric($value)) {
1333 $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
1334 $result = $this->_doQuery($query, true);
1335 if (MDB2::isError($result)) {
1336 $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
1343 // {{{ lastInsertID()
1346 * Returns the autoincrement ID if supported or $id or fetches the current
1347 * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
1349 * @param string $table name of the table into which a new row was inserted
1350 * @param string $field name of the field into which a new row was inserted
1351 * @return mixed MDB2 Error Object or id
1354 function lastInsertID($table = null, $field = null)
1356 // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
1357 // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650
1358 return $this->queryOne('SELECT LAST_INSERT_ID()');
1365 * Returns the current id of a sequence
1367 * @param string $seq_name name of the sequence
1368 * @return mixed MDB2 Error Object or id
1371 function currID($seq_name)
1373 $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
1374 $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
1375 $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
1376 return $this->queryOne($query, 'integer');
1381 * MDB2 MySQLi result driver
1384 * @category Database
1385 * @author Lukas Smith <smith@pooteeweet.org>
1387 class MDB2_Result_mysqli extends MDB2_Result_Common
1393 * Fetch a row and insert the data into an existing array.
1395 * @param int $fetchmode how the array data should be indexed
1396 * @param int $rownum number of the row where the data can be found
1397 * @return int data array on success, a MDB2 error on failure
1400 function fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
1402 if (null !== $rownum) {
1403 $seek = $this->seek($rownum);
1404 if (MDB2::isError($seek)) {
1408 if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
1409 $fetchmode = $this->db->fetchmode;
1411 if ( $fetchmode == MDB2_FETCHMODE_ASSOC
1412 || $fetchmode == MDB2_FETCHMODE_OBJECT
1414 $row = @mysqli_fetch_assoc($this->result);
1416 && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
1418 $row = array_change_key_case($row, $this->db->options['field_case']);
1421 $row = @mysqli_fetch_row($this->result);
1425 if (false === $this->result) {
1426 $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1427 'resultset has already been freed', __FUNCTION__);
1432 $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
1434 if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
1435 if (empty($this->types)) {
1436 $mode += MDB2_PORTABILITY_RTRIM;
1442 $this->db->_fixResultArrayValues($row, $mode);
1444 if ( ( $fetchmode != MDB2_FETCHMODE_ASSOC
1445 && $fetchmode != MDB2_FETCHMODE_OBJECT)
1446 && !empty($this->types)
1448 $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
1449 } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC
1450 || $fetchmode == MDB2_FETCHMODE_OBJECT)
1451 && !empty($this->types_assoc)
1453 $row = $this->db->datatype->convertResultRow($this->types_assoc, $row, $rtrim);
1455 if (!empty($this->values)) {
1456 $this->_assignBindColumns($row);
1458 if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
1459 $object_class = $this->db->options['fetch_class'];
1460 if ($object_class == 'stdClass') {
1461 $row = (object) $row;
1463 $rowObj = new $object_class($row);
1472 // {{{ _getColumnNames()
1475 * Retrieve the names of columns returned by the DBMS in a query result.
1477 * @return mixed Array variable that holds the names of columns as keys
1478 * or an MDB2 error on failure.
1479 * Some DBMS may not return any columns when the result set
1480 * does not contain any rows.
1483 function _getColumnNames()
1486 $numcols = $this->numCols();
1487 if (MDB2::isError($numcols)) {
1490 for ($column = 0; $column < $numcols; $column++) {
1491 $column_info = @mysqli_fetch_field_direct($this->result, $column);
1492 $columns[$column_info->name] = $column;
1494 if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
1495 $columns = array_change_key_case($columns, $this->db->options['field_case']);
1504 * Count the number of columns returned by the DBMS in a query result.
1506 * @return mixed integer value with the number of columns, a MDB2 error
1512 $cols = @mysqli_num_fields($this->result);
1513 if (null === $cols) {
1514 if (false === $this->result) {
1515 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1516 'resultset has already been freed', __FUNCTION__);
1518 if (null === $this->result) {
1519 return count($this->types);
1521 return $this->db->raiseError(null, null, null,
1522 'Could not get column count', __FUNCTION__);
1531 * Move the internal result pointer to the next available result
1533 * @return true on success, false if there is no more result set or an error object on failure
1536 function nextResult()
1538 $connection = $this->db->getConnection();
1539 if (MDB2::isError($connection)) {
1543 if (!@mysqli_more_results($connection)) {
1546 if (!@mysqli_next_result($connection)) {
1549 if (!($this->result = @mysqli_use_result($connection))) {
1559 * Free the internal resources associated with result.
1561 * @return boolean true on success, false if result is invalid
1567 if (is_object($this->result) && $this->db->connection) {
1568 $free = @mysqli_free_result($this->result);
1569 if (false === $free) {
1570 return $this->db->raiseError(null, null, null,
1571 'Could not free result', __FUNCTION__);
1574 } while ($this->result = $this->nextResult());
1576 $this->result = false;
1582 * MDB2 MySQLi buffered result driver
1585 * @category Database
1586 * @author Lukas Smith <smith@pooteeweet.org>
1588 class MDB2_BufferedResult_mysqli extends MDB2_Result_mysqli
1594 * Seek to a specific row in a result set
1596 * @param int $rownum number of the row where the data can be found
1597 * @return mixed MDB2_OK on success, a MDB2 error on failure
1600 function seek($rownum = 0)
1602 if ($this->rownum != ($rownum - 1) && !@mysqli_data_seek($this->result, $rownum)) {
1603 if (false === $this->result) {
1604 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1605 'resultset has already been freed', __FUNCTION__);
1607 if (null === $this->result) {
1610 return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
1611 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
1613 $this->rownum = $rownum - 1;
1621 * Check if the end of the result set has been reached
1623 * @return mixed true or false on sucess, a MDB2 error on failure
1628 $numrows = $this->numRows();
1629 if (MDB2::isError($numrows)) {
1632 return $this->rownum < ($numrows - 1);
1639 * Returns the number of rows in a result object
1641 * @return mixed MDB2 Error Object or the number of rows
1646 $rows = @mysqli_num_rows($this->result);
1647 if (null === $rows) {
1648 if (false === $this->result) {
1649 return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
1650 'resultset has already been freed', __FUNCTION__);
1652 if (null === $this->result) {
1655 return $this->db->raiseError(null, null, null,
1656 'Could not get row count', __FUNCTION__);
1665 * Move the internal result pointer to the next available result
1667 * @param a valid result resource
1668 * @return true on success, false if there is no more result set or an error object on failure
1671 function nextResult()
1673 $connection = $this->db->getConnection();
1674 if (MDB2::isError($connection)) {
1678 if (!@mysqli_more_results($connection)) {
1681 if (!@mysqli_next_result($connection)) {
1684 if (!($this->result = @mysqli_store_result($connection))) {
1692 * MDB2 MySQLi statement driver
1695 * @category Database
1696 * @author Lukas Smith <smith@pooteeweet.org>
1698 class MDB2_Statement_mysqli extends MDB2_Statement_Common
1703 * Execute a prepared query statement helper method.
1705 * @param mixed $result_class string which specifies which result class to use
1706 * @param mixed $result_wrap_class string which specifies which class to wrap results in
1708 * @return mixed MDB2_Result or integer (affected rows) on success,
1709 * a MDB2 error on failure
1712 function _execute($result_class = true, $result_wrap_class = true)
1714 if (null === $this->statement) {
1715 $result = parent::_execute($result_class, $result_wrap_class);
1718 $this->db->last_query = $this->query;
1719 $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
1720 if ($this->db->getOption('disable_query')) {
1721 $result = $this->is_manip ? 0 : null;
1725 $connection = $this->db->getConnection();
1726 if (MDB2::isError($connection)) {
1730 if (!is_object($this->statement)) {
1731 $query = 'EXECUTE '.$this->statement;
1733 if (!empty($this->positions)) {
1734 $paramReferences = array();
1735 $parameters = array(0 => $this->statement, 1 => '');
1738 foreach ($this->positions as $parameter) {
1739 if (!array_key_exists($parameter, $this->values)) {
1740 return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
1741 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
1743 $value = $this->values[$parameter];
1744 $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
1745 if (!is_object($this->statement)) {
1746 if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
1747 if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
1748 if ($match[1] == 'file://') {
1751 $value = @fopen($value, 'r');
1754 if (is_resource($value)) {
1756 while (!@feof($value)) {
1757 $data.= @fread($value, $this->db->options['lob_buffer_length']);
1765 $quoted = $this->db->quote($value, $type);
1766 if (MDB2::isError($quoted)) {
1769 $param_query = 'SET @'.$parameter.' = '.$quoted;
1770 $result = $this->db->_doQuery($param_query, true, $connection);
1771 if (MDB2::isError($result)) {
1775 if (is_resource($value) || $type == 'clob' || $type == 'blob') {
1776 $paramReferences[$i] = null;
1777 // mysqli_stmt_bind_param() requires parameters to be passed by reference
1778 $parameters[] =& $paramReferences[$i];
1779 $parameters[1].= 'b';
1780 $lobs[$i] = $parameter;
1782 $paramReferences[$i] = $this->db->quote($value, $type, false);
1783 if (MDB2::isError($paramReferences[$i])) {
1784 return $paramReferences[$i];
1786 // mysqli_stmt_bind_param() requires parameters to be passed by reference
1787 $parameters[] =& $paramReferences[$i];
1788 $parameters[1].= $this->db->datatype->mapPrepareDatatype($type);
1794 if (!is_object($this->statement)) {
1795 $query.= ' USING @'.implode(', @', array_values($this->positions));
1797 $result = call_user_func_array('mysqli_stmt_bind_param', $parameters);
1798 if (false === $result) {
1799 $err = $this->db->raiseError(null, null, null,
1800 'Unable to bind parameters', __FUNCTION__);
1804 foreach ($lobs as $i => $parameter) {
1805 $value = $this->values[$parameter];
1807 if (!is_resource($value)) {
1809 if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
1810 if ($match[1] == 'file://') {
1813 $value = @fopen($value, 'r');
1816 @fwrite($fp, $value);
1821 while (!@feof($value)) {
1822 $data = @fread($value, $this->db->options['lob_buffer_length']);
1823 @mysqli_stmt_send_long_data($this->statement, $i, $data);
1832 if (!is_object($this->statement)) {
1833 $result = $this->db->_doQuery($query, $this->is_manip, $connection);
1834 if (MDB2::isError($result)) {
1838 if ($this->is_manip) {
1839 $affected_rows = $this->db->_affectedRows($connection, $result);
1840 return $affected_rows;
1843 $result = $this->db->_wrapResult($result, $this->result_types,
1844 $result_class, $result_wrap_class, $this->limit, $this->offset);
1846 if (!mysqli_stmt_execute($this->statement)) {
1847 $err = $this->db->raiseError(null, null, null,
1848 'Unable to execute statement', __FUNCTION__);
1852 if ($this->is_manip) {
1853 $affected_rows = @mysqli_stmt_affected_rows($this->statement);
1854 return $affected_rows;
1857 if ($this->db->options['result_buffering']) {
1858 @mysqli_stmt_store_result($this->statement);
1861 $result = $this->db->_wrapResult($this->statement, $this->result_types,
1862 $result_class, $result_wrap_class, $this->limit, $this->offset);
1865 $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
1873 * Release resources allocated for the specified prepared query.
1875 * @return mixed MDB2_OK on success, a MDB2 error on failure
1880 if (null === $this->positions) {
1881 return $this->db->raiseError(MDB2_ERROR, null, null,
1882 'Prepared statement has already been freed', __FUNCTION__);
1886 if (is_object($this->statement)) {
1887 if (!@mysqli_stmt_close($this->statement)) {
1888 $result = $this->db->raiseError(null, null, null,
1889 'Could not free statement', __FUNCTION__);
1891 } elseif (null !== $this->statement) {
1892 $connection = $this->db->getConnection();
1893 if (MDB2::isError($connection)) {
1897 $query = 'DEALLOCATE PREPARE '.$this->statement;
1898 $result = $this->db->_doQuery($query, true, $connection);