Source for file adodb-lib.inc.php
Documentation is available at adodb-lib.inc.php
global $ADODB_INCLUDED_LIB;
@version V4.97 22 Jan 2008 (c) 2000-2008 John Lim (jlim\@natsoft.com.my). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Less commonly used functions are placed here to reduce size of adodb.inc.php.
$rez = preg_match('/(\sORDER\s+BY\s[^)]*)/is',$sql,$arr);
if (strpos($arr[0],'(') !== false) {
for ($i= $at, $max= strlen($sql); $i < $max; $i++ ) {
$sql = 'select * from (select a from b order by a(b),b(c) desc)';
$sql = '(select * from abc order by 1)';
// probe and guess the type
for ($j= 0;$j < $max; $j++ ) {
if (isset ($types[$i]) && $types[$i]== 'C') continue;
//print " ($i ".$types[$i]. "$v) ";
$types[$i] = 'C'; // once C, always C
// If empty string, we presume is character
// test for integer for 1st row only
// after that it is up to testing other rows to prove
// that it is not an integer
if (strlen($v) == 0) $types[$i] = 'C';
if (strpos($v,'.') !== false) $types[$i] = 'N';
if (strpos($v,'.') !== false) $types[$i] = 'N';
for ($y = 0; $y < $oldY; $y++ ) {
for ($x = $startx; $x < $oldX; $x++ ) {
$newarr[] = array($o->name);
for ($y = 0; $y < $oldY; $y++ ) {
$newarr[$x- $startx][] = $arr[$y][$x];
// See also http://www.php.net/manual/en/function.array-change-key-case.php
foreach($an_array as $key=> $value)
function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
if (count($fieldArray) == 0) return 0;
$keyCol = array($keyCol);
foreach($fieldArray as $k => $v) {
} else if ($autoQuote && !is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ and strcasecmp($v,$zthis->null2null)!= 0) {
if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
foreach ($keyCol as $v) {
if (isset ($fieldArray[$v])) {
if ($where) $where .= ' and '. $v. '='. $fieldArray[$v];
else $where = $v. '='. $fieldArray[$v];
$update = "UPDATE $table SET $uSet WHERE $where";
$rs = $zthis->Execute($update);
if ($zthis->poorAffectedRows) {
The Select count(*) wipes out any errors that the update would have returned.
http://phplens.com/lens/lensforum/msgs.php?id=5696
if ($zthis->ErrorNo()<> 0) return 0;
# affected_rows == 0 if update field values identical to old values
# for mysql - which is silly.
$cnt = $zthis->GetOne("select count(*) from $table where $where");
if ($cnt > 0) return 1; // record already exists
if (($zthis->Affected_Rows()> 0)) return 1;
// print "<p>Error=".$this->ErrorNo().'<p>';
foreach($fieldArray as $k => $v) {
if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
$insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
$rs = $zthis->Execute($insert);
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu(&$zthis, $name,$defstr= '',$blank1stItem= true,$multiple= false,
$size= 0, $selectAttr= '',$compareFields0= true)
$attr = ' multiple size="'. $size. '"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = ' size="'. $size. '"';
$s = '<select name="'. $name. '"'. $attr. ' '. $selectAttr. '>';
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"". $barr[0]. "\">". $barr[1]. "</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue= true;
else $compareFields0 = true;
$fieldsize = $zthis->FieldCount();
if ($blank1stItem && $zval== "") {
if (isset ($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
$selected = ($compareFields0) ? $zval : $zval2;
$group = rtrim($zthis->fields[2]);
if ($optgroup != $group) {
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
$s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
$s .= "\n<option selected='selected'$value>". htmlspecialchars($zval). '</option>';
$s .= "\n<option selected='selected'$value>". htmlspecialchars($zval). '</option>';
return $s . "\n</select>\n";
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu_gp(&$zthis, $name,$defstr= '',$blank1stItem= true,$multiple= false,
$size= 0, $selectAttr= '',$compareFields0= true)
$attr = ' multiple size="'. $size. '"';
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = ' size="'. $size. '"';
$s = '<select name="'. $name. '"'. $attr. ' '. $selectAttr. '>';
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"". $barr[0]. "\">". $barr[1]. "</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue= true;
else $compareFields0 = true;
$fieldsize = sizeof($zthis->fields);
if ($blank1stItem && $zval== "") {
if (isset ($zthis->fields[1]))
$zval2 = rtrim($zthis->fields[1]);
$selected = ($compareFields0) ? $zval : $zval2;
if (isset ($zthis->fields[2])) {
$group = rtrim($zthis->fields[2]);
if ($optgroup != $group) {
$s .= "\n<option selected='selected'$value>". htmlspecialchars($zval). '</option>';
$s .= "\n<option selected='selected'$value>". htmlspecialchars($zval). '</option>';
return $s . "\n</select>\n";
Count the number of records this sql statement will return by using
query rewriting heuristics...
Does not work with UNIONs, except with postgresql and oracle.
$cnt = _adodb_getcount($conn, $sql);
if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
// but this is only supported by oracle and postgresql...
if ($zthis->dataProvider == 'oci8') {
// Allow Oracle hints to be used for query optimization, Chris Wrye
if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
$rewritesql = "SELECT ". $hint[0]. " COUNT(*) FROM (". $rewritesql. ")";
$rewritesql = "SELECT COUNT(*) FROM (". $rewritesql. ")";
} else if (strncmp($zthis->databaseType,'postgres',8) == 0) {
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
// now replace SELECT ... FROM with SELECT COUNT(*) FROM
'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
// fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
// with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
// also see http://phplens.com/lens/lensforum/msgs.php?id=12752
if (isset ($rewritesql) && $rewritesql != $sql) {
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
// we only use half the time of secs2cache because the count can quickly
// become inaccurate if new records are added
$qryRecs = $zthis->CacheGetOne($secs2cache/ 2,$rewritesql,$inputarr);
$qryRecs = $zthis->GetOne($rewritesql,$inputarr);
if ($qryRecs !== false) return $qryRecs;
//--------------------------------------------
// query rewrite failed - so try slower way...
// strip off unneeded ORDER BY if no UNION
if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
$rstest = &$zthis->Execute($rewritesql,$inputarr);
if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
$qryRecs = $rstest->RecordCount();
// some databases will return -1 on MoveLast() - change to MoveNext()
$qryRecs = $rstest->_currentRow;
if ($qryRecs == - 1) return 0;
Code originally from "Cornel G" <conyg@fx.ro>
This code might not work with SQL that has UNION in it
Also if you are using CachePageExecute(), there is a strong possibility that
data will get out of synch. use CachePageExecute() only with tables that
$inputarr= false, $secs2cache= 0)
// If an invalid nrows is supplied,
// we assume a default value of 10 rows per page
if (!isset ($nrows) || $nrows <= 0) $nrows = 10;
$qryRecs = false; //count records for no offset
$lastpageno = (int) ceil($qryRecs / $nrows);
$zthis->_maxRecordCount = $qryRecs;
// ***** Here we check whether $page is the last page or
// whether we are trying to retrieve
// a page number greater than the last page number.
if ($page >= $lastpageno) {
// If page number <= 1, then we are at the first page
if (empty($page) || $page <= 1) {
// We get the data we want
$offset = $nrows * ($page- 1);
$rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
$rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
$rsreturn->_maxRecordCount = $qryRecs;
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
$rsreturn->LastPageNo($lastpageno);
if (!isset ($page) || $page <= 1) { // If page number <= 1, then we are at the first page
if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
// ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
$pagecounter = $page + 1;
$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
if ($secs2cache> 0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
while ($rstest && $rstest->EOF && $pagecounter> 0) {
$pagecounteroffset = $nrows * ($pagecounter - 1);
if ($secs2cache> 0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
if ($rstest) $rstest->Close();
if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
//... page, that is, the recordset has only 1 page.
// We get the data we want
$offset = $nrows * ($page- 1);
if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate= false,$magicq= false,$force= 2)
global $ADODB_QUOTE_FIELDNAMES;
$hasnumeric = isset ($rs->fields[0]);
// Loop through all of the fields in the recordset
for ($i= 0, $max= $rs->FieldCount(); $i < $max; $i++ ) {
// Get the field from the recordset
$field = $rs->FetchField($i);
// If the recordset field is one
// of the fields passed in then process.
// If the existing field value in the recordset
// is different from the value passed in then
// go ahead and append the field name and new value to
if ($hasnumeric) $val = $rs->fields[$i];
else if (isset ($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
else if (isset ($rs->fields[$field->name])) $val = $rs->fields[$field->name];
if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
// Set the counter for the number of fields that will be updated.
// Based on the datatype of the field
// Format the value properly for the database
$type = $rs->MetaType($field->type);
if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
$fnameq = $zthis->nameQuote. $upperfname. $zthis->nameQuote;
// is_null requires php 4.0.4
//********************************************************//
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === $zthis->null2null
// //Ignore empty values. This is allready handled in "adodb_key_exists" function.
$setFields .= $field->name . " = null, ";
$arrFields[$upperfname] = "";
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
//Set the value that was given in array, so you can give both null and empty values
if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
$setFields .= $field->name . " = null, ";
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
//********************************************************//
//we do this so each driver can customize the sql for
//DB specific column types.
//Oracle needs BLOB types to be handled with a returning clause
//postgres has special needs as well
// If there were any modified fields then build the rest of the update query.
if ($fieldUpdatedCount > 0 || $forceUpdate) {
// Get the table name from the existing query.
if (!empty($rs->tableName)) $tableName = $rs->tableName;
$tableName = $tableName[1];
// Get the full where clause excluding the word "WHERE" from
preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
// not a good hack, improvements?
if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard));
else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976
$whereClause = array(false,false);
$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
$sql = 'UPDATE '. $tableName. ' SET '. substr($setFields, 0, - 2);
if (strlen($whereClause[1]) > 0)
$sql .= ' WHERE '. $whereClause[1];
// the following is the old behaviour where null or empty fields are ignored
return (!empty($arr[$key])) || (isset ($arr[$key]) && strlen($arr[$key])> 0);
if (isset ($arr[$key])) return true;
* There is a special case of this function for the oci8 driver.
* The proper way to handle an insert w/ a blob in oracle requires
* a returning clause with bind variables and a descriptor blob.
global $ADODB_QUOTE_FIELDNAMES;
//ok we have a table name
//try and get the column info ourself.
//we need an object for the recordSet
//because we have to call MetaType.
//php can't do a $rsclass::MetaType()
$rsclass = $zthis->rsPrefix. $zthis->databaseType;
$recordSet = new $rsclass(- 1,$zthis->fetchMode);
$recordSet->connection = &$zthis;
if (is_string($cacheRS) && $cacheRS == $rs) {
$columns = $zthis->MetaColumns( $tableName );
if (isset ($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
for ($i= 0, $max= $rs->FieldCount(); $i < $max; $i++ )
$columns[] = $rs->FetchField($i);
$rs->insertSig = $cacheSig++ ;
// Loop through all of the fields in the recordset
foreach( $columns as $field ) {
if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
$fnameq = $zthis->nameQuote. $upperfname. $zthis->nameQuote;
$type = $recordSet->MetaType($field->type);
/********************************************************/
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === $zthis->null2null
case 0: // we must always set null if missing
$arrFields[$upperfname] = "";
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq);
//Set the value that was given in array, so you can give both null and empty values
if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
/*********************************************************/
//we do this so each driver can customize the sql for
//DB specific column types.
//Oracle needs BLOB types to be handled with a returning clause
//postgres has special needs as well
// Set the counter for the number of fields that will be inserted.
// Get the name of the fields to insert
$fields .= $fnameq . ", ";
// If there were any inserted fields then build the rest of the insert query.
if ($fieldInsertedCount <= 0) return false;
// Get the table name from the existing query.
if (!empty($rs->tableName)) $tableName = $rs->tableName;
$tableName = $tableName[1];
// Strip off the comma and space on the end of both the fields
$fields = substr($fields, 0, - 2);
$values = substr($values, 0, - 2);
// Append the fields and their values to the insert query.
return 'INSERT INTO '. $tableName. ' ( '. $fields. ' ) VALUES ( '. $values. ' )';
* This private method is used to help construct
* the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
* It handles the string construction of 1 column -> sql string based on
* the column type. We want to do 'safe' handling of BLOBs
* @param string the type of sql we are trying to create
* @param string column data type from the db::MetaType() method
* @param string the column name
* @param array the column value
// Based on the datatype of the field
// Format the value properly for the database
//in order to handle Blobs correctly, we need
//to do some magic for Oracle
//we need to create a new descriptor to handle
if (!empty($zthis->hasReturningInto)) {
$sql = $fnameq. '=empty_blob(), ';
//add the variable to the returning clause array
//so the user can build this later in
//case they want to add more to it
$zthis->_returningArray[$fname] = ':xx'. $fname. 'xx';
} else if (empty($arrFields[$fname])){
$sql = $fnameq. '=empty_blob(), ';
//this is to maintain compatibility
//with older adodb versions.
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
//we need to do some more magic here for long variables
//to handle these correctly in oracle.
//create a safe bind var name
//to avoid conflicts w/ dupes.
if (!empty($zthis->hasReturningInto)) {
$sql = ':xx'. $fname. 'xx, ';
$sql = $fnameq. '=:xx'. $fname. 'xx, ';
//add the variable to the returning clause array
//so the user can build this later in
//case they want to add more to it
$zthis->_returningArray[$fname] = ':xx'. $fname. 'xx';
//this is to maintain compatibility
//with older adodb versions.
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse= true)
switch($zthis->dataProvider) {
if ($type == 'L') $type = 'C';
$val = $zthis->qstr($arrFields[$fname],$magicq);
$val = $zthis->DBDate($arrFields[$fname]);
$val = $zthis->DBTimeStamp($arrFields[$fname]);
$val = $arrFields[$fname];
$val = $arrFields[$fname];
$val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic sql injection defence
if (empty($val)) $val = '0';
if ($action == 'I') return $val . ", ";
return $fnameq . "=" . $val . ", ";
foreach($inputarr as $kk=> $vv) {
if (is_null($vv)) $ss .= "($kk=>null) ";
else $ss .= "($kk=>'$vv') ";
$sqlTxt = is_array($sql) ? $sql[0] : $sql;
/*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql);
$sqlTxt = str_replace(',',', ',$sqlTxt);
$sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt);
// check if running from browser or command-line
$inBrowser = isset ($_SERVER['HTTP_USER_AGENT']);
$dbt = $zthis->databaseType;
if (isset ($zthis->dsnType)) $dbt .= '-'. $zthis->dsnType;
if ($zthis->debug === - 1)
$qID = $zthis->_query($sql,$inputarr);
Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
if ($zthis->databaseType == 'mssql') {
// ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
if($emsg = $zthis->ErrorMsg()) {
# pretty print the debug_backtrace function
$html = (isset ($_SERVER['HTTP_USER_AGENT']));
$fmt = ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
$s = ($html) ? '<pre align=left>' : '';
if (is_array($printOrArr)) $traceArr = $printOrArr;
foreach ($traceArr as $arr) {
if ($skippy) {$skippy -= 1; continue;}
for ($i= 0; $i < $tabs; $i++ ) $s .= ($html) ? ' ' : "\t";
if ($html) $s .= '<font face="Courier New,Courier">';
if (isset ($arr['class'])) $s .= $arr['class']. '.';
foreach($arr['args'] as $v) {
else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
if (strlen($v) > $MAXSTRLEN) $str .= '...';
$s .= $arr['function']. '('. implode(', ',$args). ')';
if ($html) $s .= '</pre>';
if ($printOrArr) print $s;
function _adodb_find_from($sql)
$sql = str_replace(array("\n","\r"), ' ', $sql);
$charCount = strlen($sql);
for($i = 0; $i < $charCount; $i++) {
$char = substr($sql,$i,1);
$prevChars = substr($sql,0,$i);
$nextChars = substr($sql,$i+1);
if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) {
elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) {
elseif($char == "(" && $inString === false)
elseif($char == ")" && $inString === false && $parentheseCount > 0)
elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM")
|