mysqli.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
  3. /**
  4. * The PEAR DB driver for PHP's mysqli extension
  5. * for interacting with MySQL databases
  6. *
  7. * PHP version 5
  8. *
  9. * LICENSE: This source file is subject to version 3.0 of the PHP license
  10. * that is available through the world-wide-web at the following URI:
  11. * http://www.php.net/license/3_0.txt. If you did not receive a copy of
  12. * the PHP License and are unable to obtain it through the web, please
  13. * send a note to license@php.net so we can mail you a copy immediately.
  14. *
  15. * @category Database
  16. * @package DB
  17. * @author Daniel Convissor <danielc@php.net>
  18. * @copyright 1997-2007 The PHP Group
  19. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  20. * @version CVS: $Id$
  21. * @link http://pear.php.net/package/DB
  22. */
  23. /**
  24. * Obtain the DB_common class so it can be extended from
  25. */
  26. //require_once 'DB/common.php';
  27. require_once 'common.php';
  28. /**
  29. * The methods PEAR DB uses to interact with PHP's mysqli extension
  30. * for interacting with MySQL databases
  31. *
  32. * This is for MySQL versions 4.1 and above. Requires PHP 5.
  33. *
  34. * Note that persistent connections no longer exist.
  35. *
  36. * These methods overload the ones declared in DB_common.
  37. *
  38. * @category Database
  39. * @package DB
  40. * @author Daniel Convissor <danielc@php.net>
  41. * @copyright 1997-2007 The PHP Group
  42. * @license http://www.php.net/license/3_0.txt PHP License 3.0
  43. * @version Release: 1.9.2
  44. * @link http://pear.php.net/package/DB
  45. * @since Class functional since Release 1.6.3
  46. */
  47. class DB_mysqli extends DB_common
  48. {
  49. // {{{ properties
  50. /**
  51. * The DB driver type (mysql, oci8, odbc, etc.)
  52. * @var string
  53. */
  54. public $phptype = 'mysqli';
  55. /**
  56. * The database syntax variant to be used (db2, access, etc.), if any
  57. * @var string
  58. */
  59. public $dbsyntax = 'mysqli';
  60. /**
  61. * The capabilities of this DB implementation
  62. *
  63. * The 'new_link' element contains the PHP version that first provided
  64. * new_link support for this DBMS. Contains false if it's unsupported.
  65. *
  66. * Meaning of the 'limit' element:
  67. * + 'emulate' = emulate with fetch row by number
  68. * + 'alter' = alter the query
  69. * + false = skip rows
  70. *
  71. * @var array
  72. */
  73. public $features = array(
  74. 'limit' => 'alter',
  75. 'new_link' => false,
  76. 'numrows' => true,
  77. 'pconnect' => false,
  78. 'prepare' => false,
  79. 'ssl' => true,
  80. 'transactions' => true,
  81. );
  82. /**
  83. * A mapping of native error codes to DB error codes
  84. * @var array
  85. */
  86. public $errorcode_map = array(
  87. 1004 => DB_ERROR_CANNOT_CREATE,
  88. 1005 => DB_ERROR_CANNOT_CREATE,
  89. 1006 => DB_ERROR_CANNOT_CREATE,
  90. 1007 => DB_ERROR_ALREADY_EXISTS,
  91. 1008 => DB_ERROR_CANNOT_DROP,
  92. 1022 => DB_ERROR_ALREADY_EXISTS,
  93. 1044 => DB_ERROR_ACCESS_VIOLATION,
  94. 1046 => DB_ERROR_NODBSELECTED,
  95. 1048 => DB_ERROR_CONSTRAINT,
  96. 1049 => DB_ERROR_NOSUCHDB,
  97. 1050 => DB_ERROR_ALREADY_EXISTS,
  98. 1051 => DB_ERROR_NOSUCHTABLE,
  99. 1054 => DB_ERROR_NOSUCHFIELD,
  100. 1061 => DB_ERROR_ALREADY_EXISTS,
  101. 1062 => DB_ERROR_ALREADY_EXISTS,
  102. 1064 => DB_ERROR_SYNTAX,
  103. 1091 => DB_ERROR_NOT_FOUND,
  104. 1100 => DB_ERROR_NOT_LOCKED,
  105. 1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
  106. 1142 => DB_ERROR_ACCESS_VIOLATION,
  107. 1146 => DB_ERROR_NOSUCHTABLE,
  108. 1216 => DB_ERROR_CONSTRAINT,
  109. 1217 => DB_ERROR_CONSTRAINT,
  110. 1356 => DB_ERROR_DIVZERO,
  111. 1451 => DB_ERROR_CONSTRAINT,
  112. 1452 => DB_ERROR_CONSTRAINT,
  113. );
  114. /**
  115. * The raw database connection created by PHP
  116. * @var resource
  117. */
  118. public $connection;
  119. /**
  120. * The DSN information for connecting to a database
  121. * @var array
  122. */
  123. public $dsn = array();
  124. /**
  125. * Should data manipulation queries be committed automatically?
  126. * @var bool
  127. * @access private
  128. */
  129. public $autocommit = true;
  130. /**
  131. * The quantity of transactions begun
  132. *
  133. * {@internal While this is private, it can't actually be designated
  134. * private in PHP 5 because it is directly accessed in the test suite.}}
  135. *
  136. * @var integer
  137. * @access private
  138. */
  139. public $transaction_opcount = 0;
  140. /**
  141. * The database specified in the DSN
  142. *
  143. * It's a fix to allow calls to different databases in the same script.
  144. *
  145. * @var string
  146. * @access private
  147. */
  148. public $_db = '';
  149. /**
  150. * Array for converting MYSQLI_*_FLAG constants to text values
  151. * @var array
  152. * @access public
  153. * @since Property available since Release 1.6.5
  154. */
  155. public $mysqli_flags = array(
  156. MYSQLI_NOT_NULL_FLAG => 'not_null',
  157. MYSQLI_PRI_KEY_FLAG => 'primary_key',
  158. MYSQLI_UNIQUE_KEY_FLAG => 'unique_key',
  159. MYSQLI_MULTIPLE_KEY_FLAG => 'multiple_key',
  160. MYSQLI_BLOB_FLAG => 'blob',
  161. MYSQLI_UNSIGNED_FLAG => 'unsigned',
  162. MYSQLI_ZEROFILL_FLAG => 'zerofill',
  163. MYSQLI_AUTO_INCREMENT_FLAG => 'auto_increment',
  164. MYSQLI_TIMESTAMP_FLAG => 'timestamp',
  165. MYSQLI_SET_FLAG => 'set',
  166. // MYSQLI_NUM_FLAG => 'numeric', // unnecessary
  167. // MYSQLI_PART_KEY_FLAG => 'multiple_key', // duplicatvie
  168. MYSQLI_GROUP_FLAG => 'group_by'
  169. );
  170. /**
  171. * Array for converting MYSQLI_TYPE_* constants to text values
  172. * @var array
  173. * @access public
  174. * @since Property available since Release 1.6.5
  175. */
  176. public $mysqli_types = array(
  177. MYSQLI_TYPE_DECIMAL => 'decimal',
  178. MYSQLI_TYPE_TINY => 'tinyint',
  179. MYSQLI_TYPE_SHORT => 'int',
  180. MYSQLI_TYPE_LONG => 'int',
  181. MYSQLI_TYPE_FLOAT => 'float',
  182. MYSQLI_TYPE_DOUBLE => 'double',
  183. // MYSQLI_TYPE_NULL => 'DEFAULT NULL', // let flags handle it
  184. MYSQLI_TYPE_TIMESTAMP => 'timestamp',
  185. MYSQLI_TYPE_LONGLONG => 'bigint',
  186. MYSQLI_TYPE_INT24 => 'mediumint',
  187. MYSQLI_TYPE_DATE => 'date',
  188. MYSQLI_TYPE_TIME => 'time',
  189. MYSQLI_TYPE_DATETIME => 'datetime',
  190. MYSQLI_TYPE_YEAR => 'year',
  191. MYSQLI_TYPE_NEWDATE => 'date',
  192. MYSQLI_TYPE_ENUM => 'enum',
  193. MYSQLI_TYPE_SET => 'set',
  194. MYSQLI_TYPE_TINY_BLOB => 'tinyblob',
  195. MYSQLI_TYPE_MEDIUM_BLOB => 'mediumblob',
  196. MYSQLI_TYPE_LONG_BLOB => 'longblob',
  197. MYSQLI_TYPE_BLOB => 'blob',
  198. MYSQLI_TYPE_VAR_STRING => 'varchar',
  199. MYSQLI_TYPE_STRING => 'char',
  200. MYSQLI_TYPE_GEOMETRY => 'geometry',
  201. /* These constants are conditionally compiled in ext/mysqli, so we'll
  202. * define them by number rather than constant. */
  203. 16 => 'bit',
  204. 246 => 'decimal',
  205. );
  206. // }}}
  207. // {{{ constructor
  208. /**
  209. * This constructor calls <kbd>parent::__construct()</kbd>
  210. *
  211. * @return void
  212. */
  213. public function __construct()
  214. {
  215. parent::__construct();
  216. }
  217. // }}}
  218. // {{{ connect()
  219. /**
  220. * Connect to the database server, log in and open the database
  221. *
  222. * Don't call this method directly. Use DB::connect() instead.
  223. *
  224. * PEAR DB's mysqli driver supports the following extra DSN options:
  225. * + When the 'ssl' $option passed to DB::connect() is true:
  226. * + key The path to the key file.
  227. * + cert The path to the certificate file.
  228. * + ca The path to the certificate authority file.
  229. * + capath The path to a directory that contains trusted SSL
  230. * CA certificates in pem format.
  231. * + cipher The list of allowable ciphers for SSL encryption.
  232. *
  233. * Example of how to connect using SSL:
  234. * <code>
  235. * require_once 'DB.php';
  236. *
  237. * $dsn = array(
  238. * 'phptype' => 'mysqli',
  239. * 'username' => 'someuser',
  240. * 'password' => 'apasswd',
  241. * 'hostspec' => 'localhost',
  242. * 'database' => 'thedb',
  243. * 'key' => 'client-key.pem',
  244. * 'cert' => 'client-cert.pem',
  245. * 'ca' => 'cacert.pem',
  246. * 'capath' => '/path/to/ca/dir',
  247. * 'cipher' => 'AES',
  248. * );
  249. *
  250. * $options = array(
  251. * 'ssl' => true,
  252. * );
  253. *
  254. * $db = DB::connect($dsn, $options);
  255. * if ((new PEAR)->isError($db)) {
  256. * die($db->getMessage());
  257. * }
  258. * </code>
  259. *
  260. * @param array $dsn the data source name
  261. * @param bool $persistent should the connection be persistent?
  262. *
  263. * @return int|object
  264. */
  265. public function connect($dsn, $persistent = false)
  266. {
  267. if (!PEAR::loadExtension('mysqli')) {
  268. return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND);
  269. }
  270. $this->dsn = $dsn;
  271. if ($dsn['dbsyntax']) {
  272. $this->dbsyntax = $dsn['dbsyntax'];
  273. }
  274. $ini = ini_get('track_errors');
  275. @ini_set('track_errors', 1);
  276. $php_errormsg = '';
  277. if (((int)$this->getOption('ssl')) === 1) {
  278. $init = mysqli_init();
  279. mysqli_ssl_set(
  280. $init,
  281. empty($dsn['key']) ? null : $dsn['key'],
  282. empty($dsn['cert']) ? null : $dsn['cert'],
  283. empty($dsn['ca']) ? null : $dsn['ca'],
  284. empty($dsn['capath']) ? null : $dsn['capath'],
  285. empty($dsn['cipher']) ? null : $dsn['cipher']
  286. );
  287. if ($this->connection = @mysqli_real_connect(
  288. $init,
  289. $dsn['hostspec'],
  290. $dsn['username'],
  291. $dsn['password'],
  292. $dsn['database'],
  293. $dsn['port'],
  294. $dsn['socket']
  295. )) {
  296. $this->connection = $init;
  297. }
  298. } else {
  299. $this->connection = @mysqli_connect(
  300. $dsn['hostspec'],
  301. $dsn['username'],
  302. $dsn['password'],
  303. $dsn['database'],
  304. $dsn['port'],
  305. $dsn['socket']
  306. );
  307. }
  308. @ini_set('track_errors', $ini);
  309. if (!$this->connection) {
  310. if (($err = @mysqli_connect_error()) != '') {
  311. return $this->raiseError(
  312. DB_ERROR_CONNECT_FAILED,
  313. null,
  314. null,
  315. null,
  316. $err
  317. );
  318. } else {
  319. return $this->raiseError(
  320. DB_ERROR_CONNECT_FAILED,
  321. null,
  322. null,
  323. null,
  324. $php_errormsg
  325. );
  326. }
  327. }
  328. if ($dsn['database']) {
  329. $this->_db = $dsn['database'];
  330. }
  331. return DB_OK;
  332. }
  333. // }}}
  334. // {{{ disconnect()
  335. /**
  336. * Disconnects from the database server
  337. *
  338. * @return bool TRUE on success, FALSE on failure
  339. */
  340. public function disconnect()
  341. {
  342. $ret = @mysqli_close($this->connection);
  343. $this->connection = null;
  344. return $ret;
  345. }
  346. // }}}
  347. // {{{ simpleQuery()
  348. /**
  349. * Sends a query to the database server
  350. *
  351. * @param string the SQL query string
  352. *
  353. * @return mixed + a PHP result resrouce for successful SELECT queries
  354. * + the DB_OK constant for other successful queries
  355. * + a DB_Error object on failure
  356. */
  357. public function simpleQuery($query)
  358. {
  359. $ismanip = $this->_checkManip($query);
  360. $this->last_query = $query;
  361. $query = $this->modifyQuery($query);
  362. if ($this->_db) {
  363. if (!@mysqli_select_db($this->connection, $this->_db)) {
  364. return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
  365. }
  366. }
  367. if (!$this->autocommit && $ismanip) {
  368. if ($this->transaction_opcount == 0) {
  369. $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=0');
  370. $result = @mysqli_query($this->connection, 'BEGIN');
  371. if (!$result) {
  372. return $this->mysqliRaiseError();
  373. }
  374. }
  375. $this->transaction_opcount++;
  376. }
  377. $result = @mysqli_query($this->connection, $query);
  378. if (!$result) {
  379. return $this->mysqliRaiseError();
  380. }
  381. if (is_object($result)) {
  382. return $result;
  383. }
  384. return DB_OK;
  385. }
  386. // }}}
  387. // {{{ nextResult()
  388. /**
  389. * Produces a DB_Error object regarding the current problem
  390. *
  391. * @param int $errno if the error is being manually raised pass a
  392. * DB_ERROR* constant here. If this isn't passed
  393. * the error information gathered from the DBMS.
  394. *
  395. * @return object the DB_Error object
  396. *
  397. * @see DB_common::raiseError(),
  398. * DB_mysqli::errorNative(), DB_common::errorCode()
  399. */
  400. public function mysqliRaiseError($errno = null)
  401. {
  402. if ($errno === null) {
  403. if ($this->options['portability'] & DB_PORTABILITY_ERRORS) {
  404. $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT;
  405. $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL;
  406. $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT;
  407. } else {
  408. // Doing this in case mode changes during runtime.
  409. $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS;
  410. $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT;
  411. $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS;
  412. }
  413. $errno = $this->errorCode(mysqli_errno($this->connection));
  414. }
  415. return $this->raiseError(
  416. $errno,
  417. null,
  418. null,
  419. null,
  420. @mysqli_errno($this->connection) . ' ** ' .
  421. @mysqli_error($this->connection)
  422. );
  423. }
  424. // }}}
  425. // {{{ fetchInto()
  426. /**
  427. * Move the internal mysql result pointer to the next available result.
  428. *
  429. * This method has not been implemented yet.
  430. *
  431. * @param resource $result a valid sql result resource
  432. * @return false
  433. * @access public
  434. */
  435. public function nextResult($result)
  436. {
  437. return false;
  438. }
  439. // }}}
  440. // {{{ freeResult()
  441. /**
  442. * Places a row from the result set into the given array
  443. *
  444. * Formating of the array and the data therein are configurable.
  445. * See DB_result::fetchInto() for more information.
  446. *
  447. * This method is not meant to be called directly. Use
  448. * DB_result::fetchInto() instead. It can't be declared "protected"
  449. * because DB_result is a separate object.
  450. *
  451. * @param resource $result the query result resource
  452. * @param array $arr the referenced array to put the data in
  453. * @param int $fetchmode how the resulting array should be indexed
  454. * @param int $rownum the row number to fetch (0 = first row)
  455. *
  456. * @return mixed DB_OK on success, NULL when the end of a result set is
  457. * reached or on failure
  458. *
  459. * @see DB_result::fetchInto()
  460. */
  461. public function fetchInto($result, &$arr, $fetchmode, $rownum = null)
  462. {
  463. if ($rownum !== null) {
  464. if (!@mysqli_data_seek($result, $rownum)) {
  465. return null;
  466. }
  467. }
  468. if ($fetchmode & DB_FETCHMODE_ASSOC) {
  469. $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC);
  470. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) {
  471. $arr = array_change_key_case($arr, CASE_LOWER);
  472. }
  473. } else {
  474. $arr = @mysqli_fetch_row($result);
  475. }
  476. if (!$arr) {
  477. return null;
  478. }
  479. if ($this->options['portability'] & DB_PORTABILITY_RTRIM) {
  480. /*
  481. * Even though this DBMS already trims output, we do this because
  482. * a field might have intentional whitespace at the end that
  483. * gets removed by DB_PORTABILITY_RTRIM under another driver.
  484. */
  485. $this->_rtrimArrayValues($arr);
  486. }
  487. if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) {
  488. $this->_convertNullArrayValuesToEmpty($arr);
  489. }
  490. return DB_OK;
  491. }
  492. // }}}
  493. // {{{ numCols()
  494. /**
  495. * Deletes the result set and frees the memory occupied by the result set
  496. *
  497. * This method is not meant to be called directly. Use
  498. * DB_result::free() instead. It can't be declared "protected"
  499. * because DB_result is a separate object.
  500. *
  501. * @param resource $result PHP's query result resource
  502. *
  503. * @return bool TRUE on success, FALSE if $result is invalid
  504. *
  505. * @see DB_result::free()
  506. */
  507. public function freeResult($result)
  508. {
  509. if (!$result instanceof mysqli_result) {
  510. return false;
  511. }
  512. mysqli_free_result($result);
  513. return true;
  514. }
  515. // }}}
  516. // {{{ numRows()
  517. /**
  518. * Gets the number of columns in a result set
  519. *
  520. * This method is not meant to be called directly. Use
  521. * DB_result::numCols() instead. It can't be declared "protected"
  522. * because DB_result is a separate object.
  523. *
  524. * @param resource $result PHP's query result resource
  525. *
  526. * @return int|object
  527. *
  528. * @see DB_result::numCols()
  529. */
  530. public function numCols($result)
  531. {
  532. $cols = @mysqli_num_fields($result);
  533. if (!$cols) {
  534. return $this->mysqliRaiseError();
  535. }
  536. return $cols;
  537. }
  538. // }}}
  539. // {{{ autoCommit()
  540. /**
  541. * Gets the number of rows in a result set
  542. *
  543. * This method is not meant to be called directly. Use
  544. * DB_result::numRows() instead. It can't be declared "protected"
  545. * because DB_result is a separate object.
  546. *
  547. * @param resource $result PHP's query result resource
  548. *
  549. * @return int|object
  550. *
  551. * @see DB_result::numRows()
  552. */
  553. public function numRows($result)
  554. {
  555. $rows = @mysqli_num_rows($result);
  556. if ($rows === null) {
  557. return $this->mysqliRaiseError();
  558. }
  559. return $rows;
  560. }
  561. // }}}
  562. // {{{ commit()
  563. /**
  564. * Enables or disables automatic commits
  565. *
  566. * @param bool $onoff true turns it on, false turns it off
  567. *
  568. * @return int DB_OK on success. A DB_Error object if the driver
  569. * doesn't support auto-committing transactions.
  570. */
  571. public function autoCommit($onoff = false)
  572. {
  573. // XXX if $this->transaction_opcount > 0, we should probably
  574. // issue a warning here.
  575. $this->autocommit = $onoff ? true : false;
  576. return DB_OK;
  577. }
  578. // }}}
  579. // {{{ rollback()
  580. /**
  581. * Commits the current transaction
  582. *
  583. * @return int|object
  584. */
  585. public function commit()
  586. {
  587. if ($this->transaction_opcount > 0) {
  588. if ($this->_db) {
  589. if (!@mysqli_select_db($this->connection, $this->_db)) {
  590. return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
  591. }
  592. }
  593. $result = @mysqli_query($this->connection, 'COMMIT');
  594. $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1');
  595. $this->transaction_opcount = 0;
  596. if (!$result) {
  597. return $this->mysqliRaiseError();
  598. }
  599. }
  600. return DB_OK;
  601. }
  602. // }}}
  603. // {{{ affectedRows()
  604. /**
  605. * Reverts the current transaction
  606. *
  607. * @return int|object
  608. */
  609. public function rollback()
  610. {
  611. if ($this->transaction_opcount > 0) {
  612. if ($this->_db) {
  613. if (!@mysqli_select_db($this->connection, $this->_db)) {
  614. return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
  615. }
  616. }
  617. $result = @mysqli_query($this->connection, 'ROLLBACK');
  618. $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1');
  619. $this->transaction_opcount = 0;
  620. if (!$result) {
  621. return $this->mysqliRaiseError();
  622. }
  623. }
  624. return DB_OK;
  625. }
  626. // }}}
  627. // {{{ nextId()
  628. /**
  629. * Determines the number of rows affected by a data maniuplation query
  630. *
  631. * 0 is returned for queries that don't manipulate data.
  632. *
  633. * @return int the number of rows. A DB_Error object on failure.
  634. */
  635. public function affectedRows()
  636. {
  637. if ($this->_last_query_manip) {
  638. return @mysqli_affected_rows($this->connection);
  639. } else {
  640. return 0;
  641. }
  642. }
  643. /**
  644. * Returns the next free id in a sequence
  645. *
  646. * @param string $seq_name name of the sequence
  647. * @param boolean $ondemand when true, the seqence is automatically
  648. * created if it does not exist
  649. *
  650. * @return int|object
  651. * A DB_Error object on failure.
  652. *
  653. * @see DB_common::nextID(), DB_common::getSequenceName(),
  654. * DB_mysqli::createSequence(), DB_mysqli::dropSequence()
  655. */
  656. public function nextId($seq_name, $ondemand = true)
  657. {
  658. $seqname = $this->getSequenceName($seq_name);
  659. do {
  660. $repeat = 0;
  661. $this->pushErrorHandling(PEAR_ERROR_RETURN);
  662. $result = $this->query('UPDATE ' . $seqname
  663. . ' SET id = LAST_INSERT_ID(id + 1)');
  664. $this->popErrorHandling();
  665. if ($result === DB_OK) {
  666. // COMMON CASE
  667. $id = @mysqli_insert_id($this->connection);
  668. if ($id != 0) {
  669. return $id;
  670. }
  671. // EMPTY SEQ TABLE
  672. // Sequence table must be empty for some reason,
  673. // so fill it and return 1
  674. // Obtain a user-level lock
  675. $result = $this->getOne('SELECT GET_LOCK('
  676. . "'${seqname}_lock', 10)");
  677. if (DB::isError($result)) {
  678. return $this->raiseError($result);
  679. }
  680. if ($result == 0) {
  681. return $this->mysqliRaiseError(DB_ERROR_NOT_LOCKED);
  682. }
  683. // add the default value
  684. $result = $this->query('REPLACE INTO ' . $seqname
  685. . ' (id) VALUES (0)');
  686. if (DB::isError($result)) {
  687. return $this->raiseError($result);
  688. }
  689. // Release the lock
  690. $result = $this->getOne('SELECT RELEASE_LOCK('
  691. . "'${seqname}_lock')");
  692. if (DB::isError($result)) {
  693. return $this->raiseError($result);
  694. }
  695. // We know what the result will be, so no need to try again
  696. return 1;
  697. } elseif ($ondemand && DB::isError($result) &&
  698. $result->getCode() == DB_ERROR_NOSUCHTABLE) {
  699. // ONDEMAND TABLE CREATION
  700. $result = $this->createSequence($seq_name);
  701. // Since createSequence initializes the ID to be 1,
  702. // we do not need to retrieve the ID again (or we will get 2)
  703. if (DB::isError($result)) {
  704. return $this->raiseError($result);
  705. } else {
  706. // First ID of a newly created sequence is 1
  707. return 1;
  708. }
  709. } elseif (DB::isError($result) &&
  710. $result->getCode() == DB_ERROR_ALREADY_EXISTS) {
  711. // BACKWARDS COMPAT
  712. // see _BCsequence() comment
  713. $result = $this->_BCsequence($seqname);
  714. if (DB::isError($result)) {
  715. return $this->raiseError($result);
  716. }
  717. $repeat = 1;
  718. }
  719. } while ($repeat);
  720. return $this->raiseError($result);
  721. }
  722. // }}}
  723. // {{{ dropSequence()
  724. /**
  725. * Creates a new sequence
  726. *
  727. * @param string $seq_name name of the new sequence
  728. *
  729. * @return int DB_OK on success. A DB_Error object on failure.
  730. *
  731. * @see DB_common::createSequence(), DB_common::getSequenceName(),
  732. * DB_mysqli::nextID(), DB_mysqli::dropSequence()
  733. */
  734. public function createSequence($seq_name)
  735. {
  736. $seqname = $this->getSequenceName($seq_name);
  737. $res = $this->query('CREATE TABLE ' . $seqname
  738. . ' (id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'
  739. . ' PRIMARY KEY(id))');
  740. if (DB::isError($res)) {
  741. return $res;
  742. }
  743. // insert yields value 1, nextId call will generate ID 2
  744. return $this->query("INSERT INTO ${seqname} (id) VALUES (0)");
  745. }
  746. // }}}
  747. // {{{ _BCsequence()
  748. /**
  749. * Backwards compatibility with old sequence emulation implementation
  750. * (clean up the dupes)
  751. *
  752. * @param string $seqname the sequence name to clean up
  753. *
  754. * @return bool|object
  755. *
  756. * @access private
  757. */
  758. public function _BCsequence($seqname)
  759. {
  760. // Obtain a user-level lock... this will release any previous
  761. // application locks, but unlike LOCK TABLES, it does not abort
  762. // the current transaction and is much less frequently used.
  763. $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)");
  764. if (DB::isError($result)) {
  765. return $result;
  766. }
  767. if ($result == 0) {
  768. // Failed to get the lock, can't do the conversion, bail
  769. // with a DB_ERROR_NOT_LOCKED error
  770. return $this->mysqliRaiseError(DB_ERROR_NOT_LOCKED);
  771. }
  772. $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}");
  773. if (DB::isError($highest_id)) {
  774. return $highest_id;
  775. }
  776. // This should kill all rows except the highest
  777. // We should probably do something if $highest_id isn't
  778. // numeric, but I'm at a loss as how to handle that...
  779. $result = $this->query('DELETE FROM ' . $seqname
  780. . " WHERE id <> $highest_id");
  781. if (DB::isError($result)) {
  782. return $result;
  783. }
  784. // If another thread has been waiting for this lock,
  785. // it will go thru the above procedure, but will have no
  786. // real effect
  787. $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')");
  788. if (DB::isError($result)) {
  789. return $result;
  790. }
  791. return true;
  792. }
  793. // }}}
  794. // {{{ quoteIdentifier()
  795. /**
  796. * Deletes a sequence
  797. *
  798. * @param string $seq_name name of the sequence to be deleted
  799. *
  800. * @return int DB_OK on success. A DB_Error object on failure.
  801. *
  802. * @see DB_common::dropSequence(), DB_common::getSequenceName(),
  803. * DB_mysql::nextID(), DB_mysql::createSequence()
  804. */
  805. public function dropSequence($seq_name)
  806. {
  807. return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name));
  808. }
  809. // }}}
  810. // {{{ escapeSimple()
  811. /**
  812. * Quotes a string so it can be safely used as a table or column name
  813. * (WARNING: using names that require this is a REALLY BAD IDEA)
  814. *
  815. * WARNING: Older versions of MySQL can't handle the backtick
  816. * character (<kbd>`</kbd>) in table or column names.
  817. *
  818. * @param string $str identifier name to be quoted
  819. *
  820. * @return string quoted identifier string
  821. *
  822. * @see DB_common::quoteIdentifier()
  823. * @since Method available since Release 1.6.0
  824. */
  825. public function quoteIdentifier($str)
  826. {
  827. return '`' . str_replace('`', '``', $str) . '`';
  828. }
  829. // }}}
  830. // {{{ modifyLimitQuery()
  831. /**
  832. * Escapes a string according to the current DBMS's standards
  833. *
  834. * @param string $str the string to be escaped
  835. *
  836. * @return string the escaped string
  837. *
  838. * @see DB_common::quoteSmart()
  839. * @since Method available since Release 1.6.0
  840. */
  841. public function escapeSimple($str)
  842. {
  843. return @mysqli_real_escape_string($this->connection, $str);
  844. }
  845. // }}}
  846. // {{{ mysqliRaiseError()
  847. /**
  848. * Adds LIMIT clauses to a query string according to current DBMS standards
  849. *
  850. * @param string $query the query to modify
  851. * @param int $from the row to start to fetching (0 = the first row)
  852. * @param int $count the numbers of rows to fetch
  853. * @param mixed $params array, string or numeric data to be used in
  854. * execution of the statement. Quantity of items
  855. * passed must match quantity of placeholders in
  856. * query: meaning 1 placeholder for non-array
  857. * parameters or 1 placeholder per array element.
  858. *
  859. * @return string the query string with LIMIT clauses added
  860. *
  861. * @access protected
  862. */
  863. public function modifyLimitQuery($query, $from, $count, $params = array())
  864. {
  865. if (DB::isManip($query) || $this->_next_query_manip) {
  866. return $query . " LIMIT $count";
  867. } else {
  868. return $query . " LIMIT $from, $count";
  869. }
  870. }
  871. // }}}
  872. // {{{ errorNative()
  873. /**
  874. * Gets the DBMS' native error code produced by the last query
  875. *
  876. * @return int the DBMS' error code
  877. */
  878. public function errorNative()
  879. {
  880. return @mysqli_errno($this->connection);
  881. }
  882. // }}}
  883. // {{{ tableInfo()
  884. /**
  885. * Returns information about a table or a result set
  886. *
  887. * @param object|string $result DB_result object from a query or a
  888. * string containing the name of a table.
  889. * While this also accepts a query result
  890. * resource identifier, this behavior is
  891. * deprecated.
  892. * @param int $mode a valid tableInfo mode
  893. *
  894. * @return array|object
  895. * A DB_Error object on failure.
  896. *
  897. * @see DB_common::setOption()
  898. */
  899. public function tableInfo($result, $mode = null)
  900. {
  901. if (is_string($result)) {
  902. // Fix for bug #11580.
  903. if ($this->_db) {
  904. if (!@mysqli_select_db($this->connection, $this->_db)) {
  905. return $this->mysqliRaiseError(DB_ERROR_NODBSELECTED);
  906. }
  907. }
  908. /*
  909. * Probably received a table name.
  910. * Create a result resource identifier.
  911. */
  912. $id = @mysqli_query(
  913. $this->connection,
  914. "SELECT * FROM $result LIMIT 0"
  915. );
  916. $got_string = true;
  917. } elseif (isset($result->result)) {
  918. /*
  919. * Probably received a result object.
  920. * Extract the result resource identifier.
  921. */
  922. $id = $result->result;
  923. $got_string = false;
  924. } else {
  925. /*
  926. * Probably received a result resource identifier.
  927. * Copy it.
  928. * Deprecated. Here for compatibility only.
  929. */
  930. $id = $result;
  931. $got_string = false;
  932. }
  933. if (!is_object($id) || !is_a($id, 'mysqli_result')) {
  934. return $this->mysqliRaiseError(DB_ERROR_NEED_MORE_DATA);
  935. }
  936. if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) {
  937. $case_func = 'strtolower';
  938. } else {
  939. $case_func = 'strval';
  940. }
  941. $count = @mysqli_num_fields($id);
  942. $res = array();
  943. if ($mode) {
  944. $res['num_fields'] = $count;
  945. }
  946. for ($i = 0; $i < $count; $i++) {
  947. $tmp = @mysqli_fetch_field($id);
  948. $flags = '';
  949. foreach ($this->mysqli_flags as $const => $means) {
  950. if ($tmp->flags & $const) {
  951. $flags .= $means . ' ';
  952. }
  953. }
  954. if ($tmp->def) {
  955. $flags .= 'default_' . rawurlencode($tmp->def);
  956. }
  957. $flags = trim($flags);
  958. $res[$i] = array(
  959. 'table' => $case_func($tmp->table),
  960. 'name' => $case_func($tmp->name),
  961. 'type' => isset($this->mysqli_types[$tmp->type])
  962. ? $this->mysqli_types[$tmp->type]
  963. : 'unknown',
  964. // http://bugs.php.net/?id=36579
  965. // Doc Bug #36579: mysqli_fetch_field length handling
  966. // https://bugs.php.net/bug.php?id=62426
  967. // Bug #62426: mysqli_fetch_field_direct returns incorrect
  968. // length on UTF8 fields
  969. 'len' => $tmp->length,
  970. 'flags' => $flags,
  971. );
  972. if ($mode & DB_TABLEINFO_ORDER) {
  973. $res['order'][$res[$i]['name']] = $i;
  974. }
  975. if ($mode & DB_TABLEINFO_ORDERTABLE) {
  976. $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
  977. }
  978. }
  979. // free the result only if we were called on a table
  980. if ($got_string) {
  981. @mysqli_free_result($id);
  982. }
  983. return $res;
  984. }
  985. // }}}
  986. // {{{ getSpecialQuery()
  987. /**
  988. * Obtains the query string needed for listing a given type of objects
  989. *
  990. * @param string $type the kind of objects you want to retrieve
  991. *
  992. * @return string the SQL query string or null if the driver doesn't
  993. * support the object type requested
  994. *
  995. * @access protected
  996. * @see DB_common::getListOf()
  997. */
  998. public function getSpecialQuery($type)
  999. {
  1000. switch ($type) {
  1001. case 'tables':
  1002. return 'SHOW TABLES';
  1003. case 'users':
  1004. return 'SELECT DISTINCT User FROM mysql.user';
  1005. case 'databases':
  1006. return 'SHOW DATABASES';
  1007. default:
  1008. return null;
  1009. }
  1010. }
  1011. public function getVersion()
  1012. {
  1013. return mysqli_get_server_version($this->connection);
  1014. }
  1015. // }}}
  1016. }
  1017. /*
  1018. * Local variables:
  1019. * tab-width: 4
  1020. * c-basic-offset: 4
  1021. * End:
  1022. */