3 V5.18 3 Sep 2012 (c) 2000-2012 John Lim (jlim#natsoft.com). All rights reserved.
4 Released under both BSD license and Lesser GPL library license.
5 Whenever there is any discrepancy between the two licenses,
6 the BSD license will take precedence.
9 MySQL code that does not support transactions. Use mysqlt if you need transactions.
10 Requires mysql client. Works on Windows and Unix.
12 28 Feb 2001: MetaColumns bug fix - suggested by Freek Dijkstra (phpeverywhere@macfreek.com)
15 // security - hide paths
16 if (!defined('ADODB_DIR')) die();
18 if (! defined("_ADODB_MYSQL_LAYER")) {
19 define("_ADODB_MYSQL_LAYER", 1 );
21 class ADODB_mysql extends ADOConnection {
22 var $databaseType = 'mysql';
23 var $dataProvider = 'mysql';
24 var $hasInsertID = true;
25 var $hasAffectedRows = true;
26 var $metaTablesSQL = "SELECT TABLE_NAME, CASE WHEN TABLE_TYPE = 'VIEW' THEN 'V' ELSE 'T' END FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA=SCHEMA()";
27 var $metaColumnsSQL = "SHOW COLUMNS FROM `%s`";
28 var $fmtTimeStamp = "'Y-m-d H:i:s'";
30 var $hasMoveFirst = true;
32 var $isoDates = true; // accepts dates in ISO format
33 var $sysDate = 'CURDATE()';
34 var $sysTimeStamp = 'NOW()';
35 var $hasTransactions = false;
36 var $forceNewConnect = false;
37 var $poorAffectedRows = true;
40 var $substr = "substring";
41 var $nameQuote = '`'; /// string to use to quote identifiers and names
42 var $compat323 = false; // true if compat with mysql 3.23
44 function ADODB_mysql()
46 if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_';
50 // SetCharSet - switch the client encoding
51 function SetCharSet($charset_name)
53 if (!function_exists('mysql_set_charset'))
56 if ($this->charSet !== $charset_name) {
57 $ok = @mysql_set_charset($charset_name,$this->_connectionID);
59 $this->charSet = $charset_name;
69 $arr['description'] = ADOConnection::GetOne("select version()");
70 $arr['version'] = ADOConnection::_findvers($arr['description']);
74 function IfNull( $field, $ifNull )
76 return " IFNULL($field, $ifNull) "; // if MySQL
79 function MetaProcedures($NamePattern = false, $catalog = null, $schemaPattern = null)
81 // save old fetch mode
82 global $ADODB_FETCH_MODE;
85 $save = $ADODB_FETCH_MODE;
86 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
88 if ($this->fetchMode !== FALSE) {
89 $savem = $this->SetFetchMode(FALSE);
92 $procedures = array ();
98 $likepattern = " LIKE '".$NamePattern."'";
100 $rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
101 if (is_object($rs)) {
103 // parse index data into array
104 while ($row = $rs->FetchRow()) {
105 $procedures[$row[1]] = array(
106 'type' => 'PROCEDURE',
110 'remarks' => $row[7],
115 $rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
116 if (is_object($rs)) {
117 // parse index data into array
118 while ($row = $rs->FetchRow()) {
119 $procedures[$row[1]] = array(
120 'type' => 'FUNCTION',
130 $this->SetFetchMode($savem);
133 $ADODB_FETCH_MODE = $save;
139 function MetaTables($ttype=false,$showSchema=false,$mask=false)
141 $save = $this->metaTablesSQL;
142 if ($showSchema && is_string($showSchema)) {
143 $this->metaTablesSQL .= " from $showSchema";
147 $mask = $this->qstr($mask);
148 $this->metaTablesSQL .= " like $mask";
150 $ret = ADOConnection::MetaTables($ttype,$showSchema);
152 $this->metaTablesSQL = $save;
157 function MetaIndexes ($table, $primary = FALSE, $owner=false)
159 // save old fetch mode
160 global $ADODB_FETCH_MODE;
163 $save = $ADODB_FETCH_MODE;
164 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
165 if ($this->fetchMode !== FALSE) {
166 $savem = $this->SetFetchMode(FALSE);
170 $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
174 $this->SetFetchMode($savem);
176 $ADODB_FETCH_MODE = $save;
178 if (!is_object($rs)) {
184 // parse index data into array
185 while ($row = $rs->FetchRow()) {
186 if ($primary == FALSE AND $row[2] == 'PRIMARY') {
190 if (!isset($indexes[$row[2]])) {
191 $indexes[$row[2]] = array(
192 'unique' => ($row[1] == 0),
197 $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
200 // sort columns by order in the index
201 foreach ( array_keys ($indexes) as $index )
203 ksort ($indexes[$index]['columns']);
210 // if magic quotes disabled, use mysql_real_escape_string()
211 function qstr($s,$magic_quotes=false)
213 if (is_null($s)) return 'NULL';
214 if (!$magic_quotes) {
216 if (ADODB_PHPVER >= 0x4300) {
217 if (is_resource($this->_connectionID))
218 return "'".mysql_real_escape_string($s,$this->_connectionID)."'";
220 if ($this->replaceQuote[0] == '\\'){
221 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
223 return "'".str_replace("'",$this->replaceQuote,$s)."'";
226 // undo magic quotes for "
227 $s = str_replace('\\"','"',$s);
233 return ADOConnection::GetOne('SELECT LAST_INSERT_ID()');
234 //return mysql_insert_id($this->_connectionID);
237 function GetOne($sql,$inputarr=false)
239 global $ADODB_GETONE_EOF;
240 if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) {
241 $rs = $this->SelectLimit($sql,1,-1,$inputarr);
244 if ($rs->EOF) return $ADODB_GETONE_EOF;
245 return reset($rs->fields);
248 return ADOConnection::GetOne($sql,$inputarr);
253 function BeginTrans()
255 if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver");
258 function _affectedrows()
260 return mysql_affected_rows($this->_connectionID);
263 // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
264 // Reference on Last_Insert_ID on the recommended way to simulate sequences
265 var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
266 var $_genSeqSQL = "create table %s (id int not null)";
267 var $_genSeqCountSQL = "select count(*) from %s";
268 var $_genSeq2SQL = "insert into %s values (%s)";
269 var $_dropSeqSQL = "drop table %s";
271 function CreateSequence($seqname='adodbseq',$startID=1)
273 if (empty($this->_genSeqSQL)) return false;
274 $u = strtoupper($seqname);
276 $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname));
277 if (!$ok) return false;
278 return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
282 function GenID($seqname='adodbseq',$startID=1)
284 // post-nuke sets hasGenID to false
285 if (!$this->hasGenID) return false;
287 $savelog = $this->_logsql;
288 $this->_logsql = false;
289 $getnext = sprintf($this->_genIDSQL,$seqname);
290 $holdtransOK = $this->_transOK; // save the current status
291 $rs = @$this->Execute($getnext);
293 if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset
294 $u = strtoupper($seqname);
295 $this->Execute(sprintf($this->_genSeqSQL,$seqname));
296 $cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname));
297 if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1));
298 $rs = $this->Execute($getnext);
302 $this->genID = mysql_insert_id($this->_connectionID);
307 $this->_logsql = $savelog;
311 function MetaDatabases()
313 $qid = mysql_list_dbs($this->_connectionID);
316 $max = mysql_num_rows($qid);
318 $db = mysql_tablename($qid,$i);
319 if ($db != 'mysql') $arr[] = $db;
326 // Format date column in sql string given an input format that understands Y M D
327 function SQLDate($fmt, $col=false)
329 if (!$col) $col = $this->sysTimeStamp;
330 $s = 'DATE_FORMAT('.$col.",'";
333 for ($i=0; $i < $len; $i++) {
340 $ch = substr($fmt,$i,1);
366 $s .= "'),Quarter($col)";
368 if ($len > $i+1) $s .= ",DATE_FORMAT($col,'";
408 if ($concat) $s = "CONCAT($s)";
413 // returns concatenated string
414 // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator
418 $arr = func_get_args();
420 // suggestion by andrew005@mnogo.ru
421 $s = implode(',',$arr);
422 if (strlen($s) > 0) return "CONCAT($s)";
426 function OffsetDate($dayFraction,$date=false)
428 if (!$date) $date = $this->sysDate;
430 $fraction = $dayFraction * 24 * 3600;
431 return '('. $date . ' + INTERVAL ' . $fraction.' SECOND)';
433 // return "from_unixtime(unix_timestamp($date)+$fraction)";
436 // returns true or false
437 function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
439 if (!empty($this->port)) $argHostname .= ":".$this->port;
441 if (ADODB_PHPVER >= 0x4300)
442 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
443 $this->forceNewConnect,$this->clientFlags);
444 else if (ADODB_PHPVER >= 0x4200)
445 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword,
446 $this->forceNewConnect);
448 $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword);
450 if ($this->_connectionID === false) return false;
451 if ($argDatabasename) return $this->SelectDB($argDatabasename);
455 // returns true or false
456 function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
458 if (!empty($this->port)) $argHostname .= ":".$this->port;
460 if (ADODB_PHPVER >= 0x4300)
461 $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags);
463 $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword);
464 if ($this->_connectionID === false) return false;
465 if ($this->autoRollback) $this->RollbackTrans();
466 if ($argDatabasename) return $this->SelectDB($argDatabasename);
470 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
472 $this->forceNewConnect = true;
473 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
476 function MetaColumns($table, $normalize=true)
478 $this->_findschema($table,$schema);
480 $dbName = $this->database;
481 $this->SelectDB($schema);
483 global $ADODB_FETCH_MODE;
484 $save = $ADODB_FETCH_MODE;
485 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
487 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
488 $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
491 $this->SelectDB($dbName);
494 if (isset($savem)) $this->SetFetchMode($savem);
495 $ADODB_FETCH_MODE = $save;
496 if (!is_object($rs)) {
503 $fld = new ADOFieldObject();
504 $fld->name = $rs->fields[0];
505 $type = $rs->fields[1];
507 // split type into type(length):
509 if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) {
510 $fld->type = $query_array[1];
511 $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
512 $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1;
513 } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) {
514 $fld->type = $query_array[1];
515 $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1;
516 } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) {
517 $fld->type = $query_array[1];
518 $arr = explode(",",$query_array[2]);
520 $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6
521 $fld->max_length = ($zlen > 0) ? $zlen : 1;
524 $fld->max_length = -1;
526 $fld->not_null = ($rs->fields[2] != 'YES');
527 $fld->primary_key = ($rs->fields[3] == 'PRI');
528 $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
529 $fld->binary = (strpos($type,'blob') !== false || strpos($type,'binary') !== false);
530 $fld->unsigned = (strpos($type,'unsigned') !== false);
531 $fld->zerofill = (strpos($type,'zerofill') !== false);
535 if ($d != '' && $d != 'NULL') {
536 $fld->has_default = true;
537 $fld->default_value = $d;
539 $fld->has_default = false;
543 if ($save == ADODB_FETCH_NUM) {
546 $retarr[strtoupper($fld->name)] = $fld;
555 // returns true or false
556 function SelectDB($dbName)
558 $this->database = $dbName;
559 $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
560 if ($this->_connectionID) {
561 return @mysql_select_db($dbName,$this->_connectionID);
566 // parameters use PostgreSQL convention, not MySQL
567 function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0)
569 $offsetStr =($offset>=0) ? ((integer)$offset)."," : '';
570 // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220
571 if ($nrows < 0) $nrows = '18446744073709551615';
574 $rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
576 $rs = $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr);
580 // returns queryID or false
581 function _query($sql,$inputarr=false)
583 //global $ADODB_COUNTRECS;
584 //if($ADODB_COUNTRECS)
585 return mysql_query($sql,$this->_connectionID);
586 //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6
589 /* Returns: the last error message from previous database operation */
593 if ($this->_logsql) return $this->_errorMsg;
594 if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error();
595 else $this->_errorMsg = @mysql_error($this->_connectionID);
596 return $this->_errorMsg;
599 /* Returns: the last error number from previous database operation */
602 if ($this->_logsql) return $this->_errorCode;
603 if (empty($this->_connectionID)) return @mysql_errno();
604 else return @mysql_errno($this->_connectionID);
607 // returns true or false
610 @mysql_close($this->_connectionID);
613 $this->_connectionID = false;
618 * Maximum size of C field
626 * Maximum size of X field
633 // "Innox - Juan Carlos Gonzalez" <jgonzalez#innox.com.mx>
634 function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
636 global $ADODB_FETCH_MODE;
637 if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
639 if ( !empty($owner) ) {
640 $table = "$owner.$table";
642 $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
644 $create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
645 } else $create_sql = $a_create_table[1];
649 if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
650 $foreign_keys = array();
651 $num_keys = count($matches[0]);
652 for ( $i = 0; $i < $num_keys; $i ++ ) {
653 $my_field = explode('`, `', $matches[1][$i]);
654 $ref_table = $matches[2][$i];
655 $ref_field = explode('`, `', $matches[3][$i]);
658 $ref_table = strtoupper($ref_table);
661 // see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
662 if (!isset($foreign_keys[$ref_table])) {
663 $foreign_keys[$ref_table] = array();
665 $num_fields = count($my_field);
666 for ( $j = 0; $j < $num_fields; $j ++ ) {
667 if ( $associative ) {
668 $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
670 $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
675 return $foreign_keys;
681 /*--------------------------------------------------------------------------------------
682 Class Name: Recordset
683 --------------------------------------------------------------------------------------*/
686 class ADORecordSet_mysql extends ADORecordSet{
688 var $databaseType = "mysql";
691 function ADORecordSet_mysql($queryID,$mode=false)
693 if ($mode === false) {
694 global $ADODB_FETCH_MODE;
695 $mode = $ADODB_FETCH_MODE;
699 case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
700 case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
701 case ADODB_FETCH_DEFAULT:
702 case ADODB_FETCH_BOTH:
704 $this->fetchMode = MYSQL_BOTH; break;
706 $this->adodbFetchMode = $mode;
707 $this->ADORecordSet($queryID);
712 //GLOBAL $ADODB_COUNTRECS;
713 // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1;
714 $this->_numOfRows = @mysql_num_rows($this->_queryID);
715 $this->_numOfFields = @mysql_num_fields($this->_queryID);
718 function FetchField($fieldOffset = -1)
720 if ($fieldOffset != -1) {
721 $o = @mysql_fetch_field($this->_queryID, $fieldOffset);
722 $f = @mysql_field_flags($this->_queryID,$fieldOffset);
723 if ($o) $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com)
724 //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
725 if ($o) $o->binary = (strpos($f,'binary')!== false);
727 else { /* The $fieldOffset argument is not provided thus its -1 */
728 $o = @mysql_fetch_field($this->_queryID);
729 //if ($o) $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
730 $o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
736 function GetRowAssoc($upper=true)
738 if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields;
739 else $row = ADORecordSet::GetRowAssoc($upper);
743 /* Use associative array to get fields array */
744 function Fields($colname)
746 // added @ by "Michael William Miller" <mille562@pilot.msu.edu>
747 if ($this->fetchMode != MYSQL_NUM) return @$this->fields[$colname];
750 $this->bind = array();
751 for ($i=0; $i < $this->_numOfFields; $i++) {
752 $o = $this->FetchField($i);
753 $this->bind[strtoupper($o->name)] = $i;
756 return $this->fields[$this->bind[strtoupper($colname)]];
761 if ($this->_numOfRows == 0) return false;
762 return @mysql_data_seek($this->_queryID,$row);
767 //return adodb_movenext($this);
768 //if (defined('ADODB_EXTENSION')) return adodb_movenext($this);
769 if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) {
770 $this->_currentRow += 1;
774 $this->_currentRow += 1;
782 $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
783 return is_array($this->fields);
787 @mysql_free_result($this->_queryID);
788 $this->_queryID = false;
791 function MetaType($t,$len=-1,$fieldobj=false)
795 $t = $fieldobj->type;
796 $len = $fieldobj->max_length;
799 $len = -1; // mysql max_length is not accurate
800 switch (strtoupper($t)) {
808 if ($len <= $this->blobSize) return 'C';
815 // php_mysql extension always returns 'blob' even if 'text'
816 // so we have to check whether binary...
822 return !empty($fieldobj->binary) ? 'B' : 'X';
825 case 'DATE': return 'D';
829 case 'TIMESTAMP': return 'T';
838 if (!empty($fieldobj->primary_key)) return 'R';
847 class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
848 function ADORecordSet_ext_mysql($queryID,$mode=false)
850 if ($mode === false) {
851 global $ADODB_FETCH_MODE;
852 $mode = $ADODB_FETCH_MODE;
856 case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
857 case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
858 case ADODB_FETCH_DEFAULT:
859 case ADODB_FETCH_BOTH:
861 $this->fetchMode = MYSQL_BOTH; break;
863 $this->adodbFetchMode = $mode;
864 $this->ADORecordSet($queryID);
869 return @adodb_movenext($this);