PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/adodb/drivers/adodb-mysqli.inc.php

http://github.com/moodle/moodle
PHP | 1295 lines | 899 code | 190 blank | 206 comment | 172 complexity | 29430e78c0b50a65a0a8026b8ec14c28 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /*
  3. @version v5.20.16 12-Jan-2020
  4. @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
  5. @copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
  6. Released under both BSD license and Lesser GPL library license.
  7. Whenever there is any discrepancy between the two licenses,
  8. the BSD license will take precedence.
  9. Set tabs to 8.
  10. This is the preferred driver for MySQL connections, and supports both transactional
  11. and non-transactional table types. You can use this as a drop-in replacement for both
  12. the mysql and mysqlt drivers. As of ADOdb Version 5.20.0, all other native MySQL drivers
  13. are deprecated
  14. Requires mysql client. Works on Windows and Unix.
  15. 21 October 2003: MySQLi extension implementation by Arjen de Rijke (a.de.rijke@xs4all.nl)
  16. Based on adodb 3.40
  17. */
  18. // security - hide paths
  19. if (!defined('ADODB_DIR')) die();
  20. if (! defined("_ADODB_MYSQLI_LAYER")) {
  21. define("_ADODB_MYSQLI_LAYER", 1 );
  22. // PHP5 compat...
  23. if (! defined("MYSQLI_BINARY_FLAG")) define("MYSQLI_BINARY_FLAG", 128);
  24. if (!defined('MYSQLI_READ_DEFAULT_GROUP')) define('MYSQLI_READ_DEFAULT_GROUP',1);
  25. // disable adodb extension - currently incompatible.
  26. global $ADODB_EXTENSION; $ADODB_EXTENSION = false;
  27. class ADODB_mysqli extends ADOConnection {
  28. var $databaseType = 'mysqli';
  29. var $dataProvider = 'mysql';
  30. var $hasInsertID = true;
  31. var $hasAffectedRows = true;
  32. var $metaTablesSQL = "SELECT
  33. TABLE_NAME,
  34. CASE WHEN TABLE_TYPE = 'VIEW' THEN 'V' ELSE 'T' END
  35. FROM INFORMATION_SCHEMA.TABLES
  36. WHERE TABLE_SCHEMA=";
  37. var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
  38. var $fmtTimeStamp = "'Y-m-d H:i:s'";
  39. var $hasLimit = true;
  40. var $hasMoveFirst = true;
  41. var $hasGenID = true;
  42. var $isoDates = true; // accepts dates in ISO format
  43. var $sysDate = 'CURDATE()';
  44. var $sysTimeStamp = 'NOW()';
  45. var $hasTransactions = true;
  46. var $forceNewConnect = false;
  47. var $poorAffectedRows = true;
  48. var $clientFlags = 0;
  49. var $substr = "substring";
  50. var $port = 3306; //Default to 3306 to fix HHVM bug
  51. var $socket = ''; //Default to empty string to fix HHVM bug
  52. var $_bindInputArray = false;
  53. var $nameQuote = '`'; /// string to use to quote identifiers and names
  54. var $optionFlags = array(array(MYSQLI_READ_DEFAULT_GROUP,0));
  55. var $arrayClass = 'ADORecordSet_array_mysqli';
  56. var $multiQuery = false;
  57. function __construct()
  58. {
  59. // if(!extension_loaded("mysqli"))
  60. //trigger_error("You must have the mysqli extension installed.", E_USER_ERROR);
  61. }
  62. function SetTransactionMode( $transaction_mode )
  63. {
  64. $this->_transmode = $transaction_mode;
  65. if (empty($transaction_mode)) {
  66. $this->Execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
  67. return;
  68. }
  69. if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
  70. $this->Execute("SET SESSION TRANSACTION ".$transaction_mode);
  71. }
  72. // returns true or false
  73. // To add: parameter int $port,
  74. // parameter string $socket
  75. function _connect($argHostname = NULL,
  76. $argUsername = NULL,
  77. $argPassword = NULL,
  78. $argDatabasename = NULL, $persist=false)
  79. {
  80. if(!extension_loaded("mysqli")) {
  81. return null;
  82. }
  83. $this->_connectionID = @mysqli_init();
  84. if (is_null($this->_connectionID)) {
  85. // mysqli_init only fails if insufficient memory
  86. if ($this->debug) {
  87. ADOConnection::outp("mysqli_init() failed : " . $this->ErrorMsg());
  88. }
  89. return false;
  90. }
  91. /*
  92. I suggest a simple fix which would enable adodb and mysqli driver to
  93. read connection options from the standard mysql configuration file
  94. /etc/my.cnf - "Bastien Duclaux" <bduclaux#yahoo.com>
  95. */
  96. foreach($this->optionFlags as $arr) {
  97. mysqli_options($this->_connectionID,$arr[0],$arr[1]);
  98. }
  99. //http ://php.net/manual/en/mysqli.persistconns.php
  100. if ($persist && PHP_VERSION > 5.2 && strncmp($argHostname,'p:',2) != 0) $argHostname = 'p:'.$argHostname;
  101. #if (!empty($this->port)) $argHostname .= ":".$this->port;
  102. $ok = @mysqli_real_connect($this->_connectionID,
  103. $argHostname,
  104. $argUsername,
  105. $argPassword,
  106. $argDatabasename,
  107. # PHP7 compat: port must be int. Use default port if cast yields zero
  108. (int)$this->port != 0 ? (int)$this->port : 3306,
  109. $this->socket,
  110. $this->clientFlags);
  111. if ($ok) {
  112. if ($argDatabasename) return $this->SelectDB($argDatabasename);
  113. return true;
  114. } else {
  115. if ($this->debug) {
  116. ADOConnection::outp("Could not connect : " . $this->ErrorMsg());
  117. }
  118. $this->_connectionID = null;
  119. return false;
  120. }
  121. }
  122. // returns true or false
  123. // How to force a persistent connection
  124. function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  125. {
  126. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
  127. }
  128. // When is this used? Close old connection first?
  129. // In _connect(), check $this->forceNewConnect?
  130. function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  131. {
  132. $this->forceNewConnect = true;
  133. return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
  134. }
  135. function IfNull( $field, $ifNull )
  136. {
  137. return " IFNULL($field, $ifNull) "; // if MySQL
  138. }
  139. // do not use $ADODB_COUNTRECS
  140. function GetOne($sql,$inputarr=false)
  141. {
  142. global $ADODB_GETONE_EOF;
  143. $ret = false;
  144. $rs = $this->Execute($sql,$inputarr);
  145. if ($rs) {
  146. if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
  147. else $ret = reset($rs->fields);
  148. $rs->Close();
  149. }
  150. return $ret;
  151. }
  152. function ServerInfo()
  153. {
  154. $arr['description'] = $this->GetOne("select version()");
  155. $arr['version'] = ADOConnection::_findvers($arr['description']);
  156. return $arr;
  157. }
  158. function BeginTrans()
  159. {
  160. if ($this->transOff) return true;
  161. $this->transCnt += 1;
  162. //$this->Execute('SET AUTOCOMMIT=0');
  163. mysqli_autocommit($this->_connectionID, false);
  164. $this->Execute('BEGIN');
  165. return true;
  166. }
  167. function CommitTrans($ok=true)
  168. {
  169. if ($this->transOff) return true;
  170. if (!$ok) return $this->RollbackTrans();
  171. if ($this->transCnt) $this->transCnt -= 1;
  172. $this->Execute('COMMIT');
  173. //$this->Execute('SET AUTOCOMMIT=1');
  174. mysqli_autocommit($this->_connectionID, true);
  175. return true;
  176. }
  177. function RollbackTrans()
  178. {
  179. if ($this->transOff) return true;
  180. if ($this->transCnt) $this->transCnt -= 1;
  181. $this->Execute('ROLLBACK');
  182. //$this->Execute('SET AUTOCOMMIT=1');
  183. mysqli_autocommit($this->_connectionID, true);
  184. return true;
  185. }
  186. function RowLock($tables,$where='',$col='1 as adodbignore')
  187. {
  188. if ($this->transCnt==0) $this->BeginTrans();
  189. if ($where) $where = ' where '.$where;
  190. $rs = $this->Execute("select $col from $tables $where for update");
  191. return !empty($rs);
  192. }
  193. /**
  194. * Quotes a string to be sent to the database
  195. * When there is no active connection,
  196. * @param string $s The string to quote
  197. * @param boolean $magic_quotes If false, use mysqli_real_escape_string()
  198. * if you are quoting a string extracted from a POST/GET variable,
  199. * then pass get_magic_quotes_gpc() as the second parameter. This will
  200. * ensure that the variable is not quoted twice, once by qstr() and
  201. * once by the magic_quotes_gpc.
  202. * Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
  203. * @return string Quoted string
  204. */
  205. function qstr($s, $magic_quotes = false)
  206. {
  207. if (is_null($s)) return 'NULL';
  208. if (!$magic_quotes) {
  209. // mysqli_real_escape_string() throws a warning when the given
  210. // connection is invalid
  211. if (PHP_VERSION >= 5 && $this->_connectionID) {
  212. return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
  213. }
  214. if ($this->replaceQuote[0] == '\\') {
  215. $s = adodb_str_replace(array('\\',"\0"), array('\\\\',"\\\0") ,$s);
  216. }
  217. return "'" . str_replace("'", $this->replaceQuote, $s) . "'";
  218. }
  219. // undo magic quotes for "
  220. $s = str_replace('\\"','"',$s);
  221. return "'$s'";
  222. }
  223. function _insertid()
  224. {
  225. $result = @mysqli_insert_id($this->_connectionID);
  226. if ($result == -1) {
  227. if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : " . $this->ErrorMsg());
  228. }
  229. return $result;
  230. }
  231. // Only works for INSERT, UPDATE and DELETE query's
  232. function _affectedrows()
  233. {
  234. $result = @mysqli_affected_rows($this->_connectionID);
  235. if ($result == -1) {
  236. if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : " . $this->ErrorMsg());
  237. }
  238. return $result;
  239. }
  240. // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
  241. // Reference on Last_Insert_ID on the recommended way to simulate sequences
  242. var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
  243. var $_genSeqSQL = "create table if not exists %s (id int not null)";
  244. var $_genSeqCountSQL = "select count(*) from %s";
  245. var $_genSeq2SQL = "insert into %s values (%s)";
  246. var $_dropSeqSQL = "drop table if exists %s";
  247. function CreateSequence($seqname='adodbseq',$startID=1)
  248. {
  249. if (empty($this->_genSeqSQL)) return false;
  250. $u = strtoupper($seqname);
  251. $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
  252. if (!$ok) return false;
  253. return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
  254. }
  255. function GenID($seqname='adodbseq',$startID=1)
  256. {
  257. // post-nuke sets hasGenID to false
  258. if (!$this->hasGenID) return false;
  259. $getnext = sprintf($this->_genIDSQL,$seqname);
  260. $holdtransOK = $this->_transOK; // save the current status
  261. $rs = @$this->Execute($getnext);
  262. if (!$rs) {
  263. if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
  264. $u = strtoupper($seqname);
  265. $this->Execute(sprintf($this->_genSeqSQL,$seqname));
  266. $cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
  267. if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
  268. $rs = $this->Execute($getnext);
  269. }
  270. if ($rs) {
  271. $this->genID = mysqli_insert_id($this->_connectionID);
  272. $rs->Close();
  273. } else
  274. $this->genID = 0;
  275. return $this->genID;
  276. }
  277. function MetaDatabases()
  278. {
  279. $query = "SHOW DATABASES";
  280. $ret = $this->Execute($query);
  281. if ($ret && is_object($ret)){
  282. $arr = array();
  283. while (!$ret->EOF){
  284. $db = $ret->Fields('Database');
  285. if ($db != 'mysql') $arr[] = $db;
  286. $ret->MoveNext();
  287. }
  288. return $arr;
  289. }
  290. return $ret;
  291. }
  292. function MetaIndexes ($table, $primary = FALSE, $owner = false)
  293. {
  294. // save old fetch mode
  295. global $ADODB_FETCH_MODE;
  296. $false = false;
  297. $save = $ADODB_FETCH_MODE;
  298. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  299. if ($this->fetchMode !== FALSE) {
  300. $savem = $this->SetFetchMode(FALSE);
  301. }
  302. // get index details
  303. $rs = $this->Execute(sprintf('SHOW INDEXES FROM %s',$table));
  304. // restore fetchmode
  305. if (isset($savem)) {
  306. $this->SetFetchMode($savem);
  307. }
  308. $ADODB_FETCH_MODE = $save;
  309. if (!is_object($rs)) {
  310. return $false;
  311. }
  312. $indexes = array ();
  313. // parse index data into array
  314. while ($row = $rs->FetchRow()) {
  315. if ($primary == FALSE AND $row[2] == 'PRIMARY') {
  316. continue;
  317. }
  318. if (!isset($indexes[$row[2]])) {
  319. $indexes[$row[2]] = array(
  320. 'unique' => ($row[1] == 0),
  321. 'columns' => array()
  322. );
  323. }
  324. $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
  325. }
  326. // sort columns by order in the index
  327. foreach ( array_keys ($indexes) as $index )
  328. {
  329. ksort ($indexes[$index]['columns']);
  330. }
  331. return $indexes;
  332. }
  333. // Format date column in sql string given an input format that understands Y M D
  334. function SQLDate($fmt, $col=false)
  335. {
  336. if (!$col) $col = $this->sysTimeStamp;
  337. $s = 'DATE_FORMAT('.$col.",'";
  338. $concat = false;
  339. $len = strlen($fmt);
  340. for ($i=0; $i < $len; $i++) {
  341. $ch = $fmt[$i];
  342. switch($ch) {
  343. case 'Y':
  344. case 'y':
  345. $s .= '%Y';
  346. break;
  347. case 'Q':
  348. case 'q':
  349. $s .= "'),Quarter($col)";
  350. if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
  351. else $s .= ",('";
  352. $concat = true;
  353. break;
  354. case 'M':
  355. $s .= '%b';
  356. break;
  357. case 'm':
  358. $s .= '%m';
  359. break;
  360. case 'D':
  361. case 'd':
  362. $s .= '%d';
  363. break;
  364. case 'H':
  365. $s .= '%H';
  366. break;
  367. case 'h':
  368. $s .= '%I';
  369. break;
  370. case 'i':
  371. $s .= '%i';
  372. break;
  373. case 's':
  374. $s .= '%s';
  375. break;
  376. case 'a':
  377. case 'A':
  378. $s .= '%p';
  379. break;
  380. case 'w':
  381. $s .= '%w';
  382. break;
  383. case 'l':
  384. $s .= '%W';
  385. break;
  386. default:
  387. if ($ch == '\\') {
  388. $i++;
  389. $ch = substr($fmt,$i,1);
  390. }
  391. $s .= $ch;
  392. break;
  393. }
  394. }
  395. $s.="')";
  396. if ($concat) $s = "CONCAT($s)";
  397. return $s;
  398. }
  399. // returns concatenated string
  400. // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
  401. function Concat()
  402. {
  403. $s = "";
  404. $arr = func_get_args();
  405. // suggestion by andrew005@mnogo.ru
  406. $s = implode(',',$arr);
  407. if (strlen($s) > 0) return "CONCAT($s)";
  408. else return '';
  409. }
  410. // dayFraction is a day in floating point
  411. function OffsetDate($dayFraction,$date=false)
  412. {
  413. if (!$date) $date = $this->sysDate;
  414. $fraction = $dayFraction * 24 * 3600;
  415. return $date . ' + INTERVAL ' . $fraction.' SECOND';
  416. // return "from_unixtime(unix_timestamp($date)+$fraction)";
  417. }
  418. function MetaProcedures($NamePattern = false, $catalog = null, $schemaPattern = null)
  419. {
  420. // save old fetch mode
  421. global $ADODB_FETCH_MODE;
  422. $false = false;
  423. $save = $ADODB_FETCH_MODE;
  424. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  425. if ($this->fetchMode !== FALSE) {
  426. $savem = $this->SetFetchMode(FALSE);
  427. }
  428. $procedures = array ();
  429. // get index details
  430. $likepattern = '';
  431. if ($NamePattern) {
  432. $likepattern = " LIKE '".$NamePattern."'";
  433. }
  434. $rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
  435. if (is_object($rs)) {
  436. // parse index data into array
  437. while ($row = $rs->FetchRow()) {
  438. $procedures[$row[1]] = array(
  439. 'type' => 'PROCEDURE',
  440. 'catalog' => '',
  441. 'schema' => '',
  442. 'remarks' => $row[7],
  443. );
  444. }
  445. }
  446. $rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
  447. if (is_object($rs)) {
  448. // parse index data into array
  449. while ($row = $rs->FetchRow()) {
  450. $procedures[$row[1]] = array(
  451. 'type' => 'FUNCTION',
  452. 'catalog' => '',
  453. 'schema' => '',
  454. 'remarks' => $row[7]
  455. );
  456. }
  457. }
  458. // restore fetchmode
  459. if (isset($savem)) {
  460. $this->SetFetchMode($savem);
  461. }
  462. $ADODB_FETCH_MODE = $save;
  463. return $procedures;
  464. }
  465. /**
  466. * Retrieves a list of tables based on given criteria
  467. *
  468. * @param string $ttype Table type = 'TABLE', 'VIEW' or false=both (default)
  469. * @param string $showSchema schema name, false = current schema (default)
  470. * @param string $mask filters the table by name
  471. *
  472. * @return array list of tables
  473. */
  474. function MetaTables($ttype=false,$showSchema=false,$mask=false)
  475. {
  476. $save = $this->metaTablesSQL;
  477. if ($showSchema && is_string($showSchema)) {
  478. $this->metaTablesSQL .= $this->qstr($showSchema);
  479. } else {
  480. $this->metaTablesSQL .= "schema()";
  481. }
  482. if ($mask) {
  483. $mask = $this->qstr($mask);
  484. $this->metaTablesSQL .= " AND table_name LIKE $mask";
  485. }
  486. $ret = ADOConnection::MetaTables($ttype,$showSchema);
  487. $this->metaTablesSQL = $save;
  488. return $ret;
  489. }
  490. // "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
  491. function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
  492. {
  493. global $ADODB_FETCH_MODE;
  494. if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
  495. if ( !empty($owner) ) {
  496. $table = "$owner.$table";
  497. }
  498. $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
  499. if ($associative) {
  500. $create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
  501. } else $create_sql = $a_create_table[1];
  502. $matches = array();
  503. if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
  504. $foreign_keys = array();
  505. $num_keys = count($matches[0]);
  506. for ( $i = 0; $i < $num_keys; $i ++ ) {
  507. $my_field = explode('`, `', $matches[1][$i]);
  508. $ref_table = $matches[2][$i];
  509. $ref_field = explode('`, `', $matches[3][$i]);
  510. if ( $upper ) {
  511. $ref_table = strtoupper($ref_table);
  512. }
  513. // see https://sourceforge.net/p/adodb/bugs/100/
  514. if (!isset($foreign_keys[$ref_table])) {
  515. $foreign_keys[$ref_table] = array();
  516. }
  517. $num_fields = count($my_field);
  518. for ( $j = 0; $j < $num_fields; $j ++ ) {
  519. if ( $associative ) {
  520. $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
  521. } else {
  522. $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
  523. }
  524. }
  525. }
  526. return $foreign_keys;
  527. }
  528. function MetaColumns($table, $normalize=true)
  529. {
  530. $false = false;
  531. if (!$this->metaColumnsSQL)
  532. return $false;
  533. global $ADODB_FETCH_MODE;
  534. $save = $ADODB_FETCH_MODE;
  535. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  536. if ($this->fetchMode !== false)
  537. $savem = $this->SetFetchMode(false);
  538. $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
  539. if (isset($savem)) $this->SetFetchMode($savem);
  540. $ADODB_FETCH_MODE = $save;
  541. if (!is_object($rs))
  542. return $false;
  543. $retarr = array();
  544. while (!$rs->EOF) {
  545. $fld = new ADOFieldObject();
  546. $fld->name = $rs->fields[0];
  547. $type = $rs->fields[1];
  548. // split type into type(length):
  549. $fld->scale = null;
  550. if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
  551. $fld->type = $query_array[1];
  552. $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
  553. $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
  554. } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
  555. $fld->type = $query_array[1];
  556. $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
  557. } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
  558. $fld->type = $query_array[1];
  559. $arr = explode(",",$query_array[2]);
  560. $fld->enums = $arr;
  561. $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
  562. $fld->max_length = ($zlen > 0) ? $zlen : 1;
  563. } else {
  564. $fld->type = $type;
  565. $fld->max_length = -1;
  566. }
  567. $fld->not_null = ($rs->fields[2] != 'YES');
  568. $fld->primary_key = ($rs->fields[3] == 'PRI');
  569. $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
  570. $fld->binary = (strpos($type,'blob') !== false);
  571. $fld->unsigned = (strpos($type,'unsigned') !== false);
  572. $fld->zerofill = (strpos($type,'zerofill') !== false);
  573. if (!$fld->binary) {
  574. $d = $rs->fields[4];
  575. if ($d != '' && $d != 'NULL') {
  576. $fld->has_default = true;
  577. $fld->default_value = $d;
  578. } else {
  579. $fld->has_default = false;
  580. }
  581. }
  582. if ($save == ADODB_FETCH_NUM) {
  583. $retarr[] = $fld;
  584. } else {
  585. $retarr[strtoupper($fld->name)] = $fld;
  586. }
  587. $rs->MoveNext();
  588. }
  589. $rs->Close();
  590. return $retarr;
  591. }
  592. // returns true or false
  593. function SelectDB($dbName)
  594. {
  595. // $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
  596. $this->database = $dbName;
  597. $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
  598. if ($this->_connectionID) {
  599. $result = @mysqli_select_db($this->_connectionID, $dbName);
  600. if (!$result) {
  601. ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
  602. }
  603. return $result;
  604. }
  605. return false;
  606. }
  607. // parameters use PostgreSQL convention, not MySQL
  608. function SelectLimit($sql,
  609. $nrows = -1,
  610. $offset = -1,
  611. $inputarr = false,
  612. $secs = 0)
  613. {
  614. $nrows = (int) $nrows;
  615. $offset = (int) $offset;
  616. $offsetStr = ($offset >= 0) ? "$offset," : '';
  617. if ($nrows < 0) $nrows = '18446744073709551615';
  618. if ($secs)
  619. $rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows" , $inputarr );
  620. else
  621. $rs = $this->Execute($sql . " LIMIT $offsetStr$nrows" , $inputarr );
  622. return $rs;
  623. }
  624. function Prepare($sql)
  625. {
  626. return $sql;
  627. $stmt = $this->_connectionID->prepare($sql);
  628. if (!$stmt) {
  629. echo $this->ErrorMsg();
  630. return $sql;
  631. }
  632. return array($sql,$stmt);
  633. }
  634. // returns queryID or false
  635. function _query($sql, $inputarr)
  636. {
  637. global $ADODB_COUNTRECS;
  638. // Move to the next recordset, or return false if there is none. In a stored proc
  639. // call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
  640. // returns false. I think this is because the last "recordset" is actually just the
  641. // return value of the stored proc (ie the number of rows affected).
  642. // Commented out for reasons of performance. You should retrieve every recordset yourself.
  643. // if (!mysqli_next_result($this->connection->_connectionID)) return false;
  644. if (is_array($sql)) {
  645. // Prepare() not supported because mysqli_stmt_execute does not return a recordset, but
  646. // returns as bound variables.
  647. $stmt = $sql[1];
  648. $a = '';
  649. foreach($inputarr as $k => $v) {
  650. if (is_string($v)) $a .= 's';
  651. else if (is_integer($v)) $a .= 'i';
  652. else $a .= 'd';
  653. }
  654. $fnarr = array_merge( array($stmt,$a) , $inputarr);
  655. $ret = call_user_func_array('mysqli_stmt_bind_param',$fnarr);
  656. $ret = mysqli_stmt_execute($stmt);
  657. return $ret;
  658. }
  659. /*
  660. if (!$mysql_res = mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
  661. if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
  662. return false;
  663. }
  664. return $mysql_res;
  665. */
  666. if ($this->multiQuery) {
  667. $rs = mysqli_multi_query($this->_connectionID, $sql.';');
  668. if ($rs) {
  669. $rs = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->_connectionID ) : @mysqli_use_result( $this->_connectionID );
  670. return $rs ? $rs : true; // mysqli_more_results( $this->_connectionID )
  671. }
  672. } else {
  673. $rs = mysqli_query($this->_connectionID, $sql, $ADODB_COUNTRECS ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
  674. if ($rs) return $rs;
  675. }
  676. if($this->debug)
  677. ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
  678. return false;
  679. }
  680. /* Returns: the last error message from previous database operation */
  681. function ErrorMsg()
  682. {
  683. if (empty($this->_connectionID))
  684. $this->_errorMsg = @mysqli_connect_error();
  685. else
  686. $this->_errorMsg = @mysqli_error($this->_connectionID);
  687. return $this->_errorMsg;
  688. }
  689. /* Returns: the last error number from previous database operation */
  690. function ErrorNo()
  691. {
  692. if (empty($this->_connectionID))
  693. return @mysqli_connect_errno();
  694. else
  695. return @mysqli_errno($this->_connectionID);
  696. }
  697. // returns true or false
  698. function _close()
  699. {
  700. @mysqli_close($this->_connectionID);
  701. $this->_connectionID = false;
  702. }
  703. /*
  704. * Maximum size of C field
  705. */
  706. function CharMax()
  707. {
  708. return 255;
  709. }
  710. /*
  711. * Maximum size of X field
  712. */
  713. function TextMax()
  714. {
  715. return 4294967295;
  716. }
  717. // this is a set of functions for managing client encoding - very important if the encodings
  718. // of your database and your output target (i.e. HTML) don't match
  719. // for instance, you may have UTF8 database and server it on-site as latin1 etc.
  720. // GetCharSet - get the name of the character set the client is using now
  721. // Under Windows, the functions should work with MySQL 4.1.11 and above, the set of charsets supported
  722. // depends on compile flags of mysql distribution
  723. function GetCharSet()
  724. {
  725. //we will use ADO's builtin property charSet
  726. if (!method_exists($this->_connectionID,'character_set_name'))
  727. return false;
  728. $this->charSet = @$this->_connectionID->character_set_name();
  729. if (!$this->charSet) {
  730. return false;
  731. } else {
  732. return $this->charSet;
  733. }
  734. }
  735. // SetCharSet - switch the client encoding
  736. function SetCharSet($charset_name)
  737. {
  738. if (!method_exists($this->_connectionID,'set_charset')) {
  739. return false;
  740. }
  741. if ($this->charSet !== $charset_name) {
  742. $if = @$this->_connectionID->set_charset($charset_name);
  743. return ($if === true & $this->GetCharSet() == $charset_name);
  744. } else {
  745. return true;
  746. }
  747. }
  748. }
  749. /*--------------------------------------------------------------------------------------
  750. Class Name: Recordset
  751. --------------------------------------------------------------------------------------*/
  752. class ADORecordSet_mysqli extends ADORecordSet{
  753. var $databaseType = "mysqli";
  754. var $canSeek = true;
  755. function __construct($queryID, $mode = false)
  756. {
  757. if ($mode === false) {
  758. global $ADODB_FETCH_MODE;
  759. $mode = $ADODB_FETCH_MODE;
  760. }
  761. switch ($mode) {
  762. case ADODB_FETCH_NUM:
  763. $this->fetchMode = MYSQLI_NUM;
  764. break;
  765. case ADODB_FETCH_ASSOC:
  766. $this->fetchMode = MYSQLI_ASSOC;
  767. break;
  768. case ADODB_FETCH_DEFAULT:
  769. case ADODB_FETCH_BOTH:
  770. default:
  771. $this->fetchMode = MYSQLI_BOTH;
  772. break;
  773. }
  774. $this->adodbFetchMode = $mode;
  775. parent::__construct($queryID);
  776. }
  777. function _initrs()
  778. {
  779. global $ADODB_COUNTRECS;
  780. $this->_numOfRows = $ADODB_COUNTRECS ? @mysqli_num_rows($this->_queryID) : -1;
  781. $this->_numOfFields = @mysqli_num_fields($this->_queryID);
  782. }
  783. /*
  784. 1 = MYSQLI_NOT_NULL_FLAG
  785. 2 = MYSQLI_PRI_KEY_FLAG
  786. 4 = MYSQLI_UNIQUE_KEY_FLAG
  787. 8 = MYSQLI_MULTIPLE_KEY_FLAG
  788. 16 = MYSQLI_BLOB_FLAG
  789. 32 = MYSQLI_UNSIGNED_FLAG
  790. 64 = MYSQLI_ZEROFILL_FLAG
  791. 128 = MYSQLI_BINARY_FLAG
  792. 256 = MYSQLI_ENUM_FLAG
  793. 512 = MYSQLI_AUTO_INCREMENT_FLAG
  794. 1024 = MYSQLI_TIMESTAMP_FLAG
  795. 2048 = MYSQLI_SET_FLAG
  796. 32768 = MYSQLI_NUM_FLAG
  797. 16384 = MYSQLI_PART_KEY_FLAG
  798. 32768 = MYSQLI_GROUP_FLAG
  799. 65536 = MYSQLI_UNIQUE_FLAG
  800. 131072 = MYSQLI_BINCMP_FLAG
  801. */
  802. function FetchField($fieldOffset = -1)
  803. {
  804. $fieldnr = $fieldOffset;
  805. if ($fieldOffset != -1) {
  806. $fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
  807. }
  808. $o = @mysqli_fetch_field($this->_queryID);
  809. if (!$o) return false;
  810. //Fix for HHVM
  811. if ( !isset($o->flags) ) {
  812. $o->flags = 0;
  813. }
  814. /* Properties of an ADOFieldObject as set by MetaColumns */
  815. $o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
  816. $o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
  817. $o->auto_increment = $o->flags & MYSQLI_AUTO_INCREMENT_FLAG;
  818. $o->binary = $o->flags & MYSQLI_BINARY_FLAG;
  819. // $o->blob = $o->flags & MYSQLI_BLOB_FLAG; /* not returned by MetaColumns */
  820. $o->unsigned = $o->flags & MYSQLI_UNSIGNED_FLAG;
  821. return $o;
  822. }
  823. function GetRowAssoc($upper = ADODB_ASSOC_CASE)
  824. {
  825. if ($this->fetchMode == MYSQLI_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) {
  826. return $this->fields;
  827. }
  828. $row = ADORecordSet::GetRowAssoc($upper);
  829. return $row;
  830. }
  831. /* Use associative array to get fields array */
  832. function Fields($colname)
  833. {
  834. if ($this->fetchMode != MYSQLI_NUM) {
  835. return @$this->fields[$colname];
  836. }
  837. if (!$this->bind) {
  838. $this->bind = array();
  839. for ($i = 0; $i < $this->_numOfFields; $i++) {
  840. $o = $this->FetchField($i);
  841. $this->bind[strtoupper($o->name)] = $i;
  842. }
  843. }
  844. return $this->fields[$this->bind[strtoupper($colname)]];
  845. }
  846. function _seek($row)
  847. {
  848. if ($this->_numOfRows == 0 || $row < 0) {
  849. return false;
  850. }
  851. mysqli_data_seek($this->_queryID, $row);
  852. $this->EOF = false;
  853. return true;
  854. }
  855. function NextRecordSet()
  856. {
  857. global $ADODB_COUNTRECS;
  858. mysqli_free_result($this->_queryID);
  859. $this->_queryID = -1;
  860. // Move to the next recordset, or return false if there is none. In a stored proc
  861. // call, mysqli_next_result returns true for the last "recordset", but mysqli_store_result
  862. // returns false. I think this is because the last "recordset" is actually just the
  863. // return value of the stored proc (ie the number of rows affected).
  864. if(!mysqli_next_result($this->connection->_connectionID)) {
  865. return false;
  866. }
  867. // CD: There is no $this->_connectionID variable, at least in the ADO version I'm using
  868. $this->_queryID = ($ADODB_COUNTRECS) ? @mysqli_store_result( $this->connection->_connectionID )
  869. : @mysqli_use_result( $this->connection->_connectionID );
  870. if(!$this->_queryID) {
  871. return false;
  872. }
  873. $this->_inited = false;
  874. $this->bind = false;
  875. $this->_currentRow = -1;
  876. $this->Init();
  877. return true;
  878. }
  879. // 10% speedup to move MoveNext to child class
  880. // This is the only implementation that works now (23-10-2003).
  881. // Other functions return no or the wrong results.
  882. function MoveNext()
  883. {
  884. if ($this->EOF) return false;
  885. $this->_currentRow++;
  886. $this->fields = @mysqli_fetch_array($this->_queryID,$this->fetchMode);
  887. if (is_array($this->fields)) {
  888. $this->_updatefields();
  889. return true;
  890. }
  891. $this->EOF = true;
  892. return false;
  893. }
  894. function _fetch()
  895. {
  896. $this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);
  897. $this->_updatefields();
  898. return is_array($this->fields);
  899. }
  900. function _close()
  901. {
  902. //if results are attached to this pointer from Stored Proceedure calls, the next standard query will die 2014
  903. //only a problem with persistant connections
  904. if(isset($this->connection->_connectionID) && $this->connection->_connectionID) {
  905. while(mysqli_more_results($this->connection->_connectionID)){
  906. mysqli_next_result($this->connection->_connectionID);
  907. }
  908. }
  909. if($this->_queryID instanceof mysqli_result) {
  910. mysqli_free_result($this->_queryID);
  911. }
  912. $this->_queryID = false;
  913. }
  914. /*
  915. 0 = MYSQLI_TYPE_DECIMAL
  916. 1 = MYSQLI_TYPE_CHAR
  917. 1 = MYSQLI_TYPE_TINY
  918. 2 = MYSQLI_TYPE_SHORT
  919. 3 = MYSQLI_TYPE_LONG
  920. 4 = MYSQLI_TYPE_FLOAT
  921. 5 = MYSQLI_TYPE_DOUBLE
  922. 6 = MYSQLI_TYPE_NULL
  923. 7 = MYSQLI_TYPE_TIMESTAMP
  924. 8 = MYSQLI_TYPE_LONGLONG
  925. 9 = MYSQLI_TYPE_INT24
  926. 10 = MYSQLI_TYPE_DATE
  927. 11 = MYSQLI_TYPE_TIME
  928. 12 = MYSQLI_TYPE_DATETIME
  929. 13 = MYSQLI_TYPE_YEAR
  930. 14 = MYSQLI_TYPE_NEWDATE
  931. 247 = MYSQLI_TYPE_ENUM
  932. 248 = MYSQLI_TYPE_SET
  933. 249 = MYSQLI_TYPE_TINY_BLOB
  934. 250 = MYSQLI_TYPE_MEDIUM_BLOB
  935. 251 = MYSQLI_TYPE_LONG_BLOB
  936. 252 = MYSQLI_TYPE_BLOB
  937. 253 = MYSQLI_TYPE_VAR_STRING
  938. 254 = MYSQLI_TYPE_STRING
  939. 255 = MYSQLI_TYPE_GEOMETRY
  940. */
  941. function MetaType($t, $len = -1, $fieldobj = false)
  942. {
  943. if (is_object($t)) {
  944. $fieldobj = $t;
  945. $t = $fieldobj->type;
  946. $len = $fieldobj->max_length;
  947. }
  948. $len = -1; // mysql max_length is not accurate
  949. switch (strtoupper($t)) {
  950. case 'STRING':
  951. case 'CHAR':
  952. case 'VARCHAR':
  953. case 'TINYBLOB':
  954. case 'TINYTEXT':
  955. case 'ENUM':
  956. case 'SET':
  957. case MYSQLI_TYPE_TINY_BLOB :
  958. #case MYSQLI_TYPE_CHAR :
  959. case MYSQLI_TYPE_STRING :
  960. case MYSQLI_TYPE_ENUM :
  961. case MYSQLI_TYPE_SET :
  962. case 253 :
  963. if ($len <= $this->blobSize) return 'C';
  964. case 'TEXT':
  965. case 'LONGTEXT':
  966. case 'MEDIUMTEXT':
  967. return 'X';
  968. // php_mysql extension always returns 'blob' even if 'text'
  969. // so we have to check whether binary...
  970. case 'IMAGE':
  971. case 'LONGBLOB':
  972. case 'BLOB':
  973. case 'MEDIUMBLOB':
  974. case MYSQLI_TYPE_BLOB :
  975. case MYSQLI_TYPE_LONG_BLOB :
  976. case MYSQLI_TYPE_MEDIUM_BLOB :
  977. return !empty($fieldobj->binary) ? 'B' : 'X';
  978. case 'YEAR':
  979. case 'DATE':
  980. case MYSQLI_TYPE_DATE :
  981. case MYSQLI_TYPE_YEAR :
  982. return 'D';
  983. case 'TIME':
  984. case 'DATETIME':
  985. case 'TIMESTAMP':
  986. case MYSQLI_TYPE_DATETIME :
  987. case MYSQLI_TYPE_NEWDATE :
  988. case MYSQLI_TYPE_TIME :
  989. case MYSQLI_TYPE_TIMESTAMP :
  990. return 'T';
  991. case 'INT':
  992. case 'INTEGER':
  993. case 'BIGINT':
  994. case 'TINYINT':
  995. case 'MEDIUMINT':
  996. case 'SMALLINT':
  997. case MYSQLI_TYPE_INT24 :
  998. case MYSQLI_TYPE_LONG :
  999. case MYSQLI_TYPE_LONGLONG :
  1000. case MYSQLI_TYPE_SHORT :
  1001. case MYSQLI_TYPE_TINY :
  1002. if (!empty($fieldobj->primary_key)) return 'R';
  1003. return 'I';
  1004. // Added floating-point types
  1005. // Maybe not necessery.
  1006. case 'FLOAT':
  1007. case 'DOUBLE':
  1008. // case 'DOUBLE PRECISION':
  1009. case 'DECIMAL':
  1010. case 'DEC':
  1011. case 'FIXED':
  1012. default:
  1013. //if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
  1014. return 'N';
  1015. }
  1016. } // function
  1017. } // rs class
  1018. }
  1019. class ADORecordSet_array_mysqli extends ADORecordSet_array {
  1020. function __construct($id=-1,$mode=false)
  1021. {
  1022. parent::__construct($id,$mode);
  1023. }
  1024. function MetaType($t, $len = -1, $fieldobj = false)
  1025. {
  1026. if (is_object($t)) {
  1027. $fieldobj = $t;
  1028. $t = $fieldobj->type;
  1029. $len = $fieldobj->max_length;
  1030. }
  1031. $len = -1; // mysql max_length is not accurate
  1032. switch (strtoupper($t)) {
  1033. case 'STRING':
  1034. case 'CHAR':
  1035. case 'VARCHAR':
  1036. case 'TINYBLOB':
  1037. case 'TINYTEXT':
  1038. case 'ENUM':
  1039. case 'SET':
  1040. case MYSQLI_TYPE_TINY_BLOB :
  1041. #case MYSQLI_TYPE_CHAR :
  1042. case MYSQLI_TYPE_STRING :
  1043. case MYSQLI_TYPE_ENUM :
  1044. case MYSQLI_TYPE_SET :
  1045. case 253 :
  1046. if ($len <= $this->blobSize) return 'C';
  1047. case 'TEXT':
  1048. case 'LONGTEXT':
  1049. case 'MEDIUMTEXT':
  1050. return 'X';
  1051. // php_mysql extension always returns 'blob' even if 'text'
  1052. // so we have to check whether binary...
  1053. case 'IMAGE':
  1054. case 'LONGBLOB':
  1055. case 'BLOB':
  1056. case 'MEDIUMBLOB':
  1057. case MYSQLI_TYPE_BLOB :
  1058. case MYSQLI_TYPE_LONG_BLOB :
  1059. case MYSQLI_TYPE_MEDIUM_BLOB :
  1060. return !empty($fieldobj->binary) ? 'B' : 'X';
  1061. case 'YEAR':
  1062. case 'DATE':
  1063. case MYSQLI_TYPE_DATE :
  1064. case MYSQLI_TYPE_YEAR :
  1065. return 'D';
  1066. case 'TIME':
  1067. case 'DATETIME':
  1068. case 'TIMESTAMP':
  1069. case MYSQLI_TYPE_DATETIME :
  1070. case MYSQLI_TYPE_NEWDATE :
  1071. case MYSQLI_TYPE_TIME :
  1072. case MYSQLI_TYPE_TIMESTAMP :
  1073. return 'T';
  1074. case 'INT':
  1075. case 'INTEGER':
  1076. case 'BIGINT':
  1077. case 'TINYINT':
  1078. case 'MEDIUMINT':
  1079. case 'SMALLINT':
  1080. case MYSQLI_TYPE_INT24 :
  1081. case MYSQLI_TYPE_LONG :
  1082. case MYSQLI_TYPE_LONGLONG :
  1083. case MYSQLI_TYPE_SHORT :
  1084. case MYSQLI_TYPE_TINY :
  1085. if (!empty($fieldobj->primary_key)) return 'R';
  1086. return 'I';
  1087. // Added floating-point types
  1088. // Maybe not necessery.
  1089. case 'FLOAT':
  1090. case 'DOUBLE':
  1091. // case 'DOUBLE PRECISION':
  1092. case 'DECIMAL':
  1093. case 'DEC':
  1094. case 'FIXED':
  1095. default:
  1096. //if (!is_numeric($t)) echo "<p>--- Error in type matching $t -----</p>";
  1097. return 'N';
  1098. }
  1099. } // function
  1100. }