3 global $ADODB_INCLUDED_LIB;
4 $ADODB_INCLUDED_LIB = 1;
7 @version V4.22 15 Apr 2004 (c) 2000-2004 John Lim (jlim\@natsoft.com.my). All rights reserved.
8 Released under both BSD license and Lesser GPL library license.
9 Whenever there is any discrepancy between the two licenses,
10 the BSD license will take precedence. See License.txt.
11 Set tabs to 4 for best viewing.
13 Less commonly used functions are placed here to reduce size of adodb.inc.php.
17 // Force key to upper.
18 // See also http://www.php.net/manual/en/function.array-change-key-case.php
19 function _array_change_key_case($an_array)
21 if (is_array($an_array)) {
22 foreach($an_array as $key=>$value)
23 $new_array[strtoupper($key)] = $value;
31 function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
33 if (count($fieldArray) == 0) return 0;
37 if (!is_array($keyCol)) {
38 $keyCol = array($keyCol);
40 foreach($fieldArray as $k => $v) {
41 if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {
42 $v = $zthis->qstr($v);
45 if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
55 foreach ($keyCol as $v) {
56 if ($where) $where .= " and $v=$fieldArray[$v]";
57 else $where = "$v=$fieldArray[$v]";
60 if ($uSet && $where) {
61 $update = "UPDATE $table SET $uSet WHERE $where";
63 $rs = $zthis->Execute($update);
65 if ($zthis->poorAffectedRows) {
67 The Select count(*) wipes out any errors that the update would have returned.
68 http://phplens.com/lens/lensforum/msgs.php?id=5696
70 if ($zthis->ErrorNo()<>0) return 0;
72 # affected_rows == 0 if update field values identical to old values
73 # for mysql - which is silly.
75 $cnt = $zthis->GetOne("select count(*) from $table where $where");
76 if ($cnt > 0) return 1; // record already exists
78 if (($zthis->Affected_Rows()>0)) return 1;
81 // print "<p>Error=".$this->ErrorNo().'<p>';
83 foreach($fieldArray as $k => $v) {
84 if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
95 $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
96 $rs = $zthis->Execute($insert);
100 // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
101 function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
102 $size=0, $selectAttr='',$compareFields0=true)
106 if ($multiple or is_array($defstr)) {
107 if ($size==0) $size=5;
108 $attr = " multiple size=$size";
109 if (!strpos($name,'[]')) $name .= '[]';
110 } else if ($size) $attr = " size=$size";
113 $s = "<select name=\"$name\"$attr $selectAttr>";
115 if (is_string($blank1stItem)) {
116 $barr = explode(':',$blank1stItem);
117 if (sizeof($barr) == 1) $barr[] = '';
118 $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
119 } else $s .= "\n<option></option>";
121 if ($zthis->FieldCount() > 1) $hasvalue=true;
122 else $compareFields0 = true;
125 while(!$zthis->EOF) {
126 $zval = rtrim(reset($zthis->fields));
127 if (sizeof($zthis->fields) > 1) {
128 if (isset($zthis->fields[1]))
129 $zval2 = rtrim($zthis->fields[1]);
131 $zval2 = rtrim(next($zthis->fields));
133 $selected = ($compareFields0) ? $zval : $zval2;
135 if ($blank1stItem && $zval=="") {
140 $value = ' value="'.htmlspecialchars($zval2).'"';
142 if (is_array($defstr)) {
144 if (in_array($selected,$defstr))
145 $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
147 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
150 if (strcasecmp($selected,$defstr)==0)
151 $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
153 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
158 return $s ."\n</select>\n";
162 Count the number of records this sql statement will return by using
163 query rewriting techniques...
165 Does not work with UNIONs.
167 function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
171 if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
172 // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
173 // but this is only supported by oracle and postgresql...
174 if ($zthis->dataProvider == 'oci8') {
176 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
177 $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
179 } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') {
181 $info = $zthis->ServerInfo();
182 if (substr($info['version'],0,3) >= 7.1) { // good till version 999
183 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
184 $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
188 // now replace SELECT ... FROM with SELECT COUNT(*) FROM
190 $rewritesql = preg_replace(
191 '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
193 // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
194 // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
195 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
198 if (isset($rewritesql) && $rewritesql != $sql) {
200 // we only use half the time of secs2cache because the count can quickly
201 // become inaccurate if new records are added
202 $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
205 $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
207 if ($qryRecs !== false) return $qryRecs;
210 //--------------------------------------------
211 // query rewrite failed - so try slower way...
213 // strip off unneeded ORDER BY
214 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
215 $rstest = &$zthis->Execute($rewritesql,$inputarr);
217 $qryRecs = $rstest->RecordCount();
218 if ($qryRecs == -1) {
219 global $ADODB_EXTENSION;
220 // some databases will return -1 on MoveLast() - change to MoveNext()
221 if ($ADODB_EXTENSION) {
222 while(!$rstest->EOF) {
223 adodb_movenext($rstest);
226 while(!$rstest->EOF) {
230 $qryRecs = $rstest->_currentRow;
233 if ($qryRecs == -1) return 0;
240 Code originally from "Cornel G" <conyg@fx.ro>
242 This code will not work with SQL that has UNION in it
244 Also if you are using CachePageExecute(), there is a strong possibility that
245 data will get out of synch. use CachePageExecute() only with tables that
248 function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
249 $inputarr=false, $secs2cache=0)
251 $atfirstpage = false;
255 // If an invalid nrows is supplied,
256 // we assume a default value of 10 rows per page
257 if (!isset($nrows) || $nrows <= 0) $nrows = 10;
259 $qryRecs = false; //count records for no offset
261 $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
262 $lastpageno = (int) ceil($qryRecs / $nrows);
263 $zthis->_maxRecordCount = $qryRecs;
265 // If page number <= 1, then we are at the first page
266 if (!isset($page) || $page <= 1) {
271 // ***** Here we check whether $page is the last page or
272 // whether we are trying to retrieve
273 // a page number greater than the last page number.
274 if ($page >= $lastpageno) {
279 // We get the data we want
280 $offset = $nrows * ($page-1);
282 $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
284 $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
287 // Before returning the RecordSet, we set the pagination properties we need
289 $rsreturn->_maxRecordCount = $qryRecs;
290 $rsreturn->rowsPerPage = $nrows;
291 $rsreturn->AbsolutePage($page);
292 $rsreturn->AtFirstPage($atfirstpage);
293 $rsreturn->AtLastPage($atlastpage);
294 $rsreturn->LastPageNo($lastpageno);
299 // Iván Oliva version
300 function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
303 $atfirstpage = false;
306 if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page
310 if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
312 // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
313 // the last page number.
314 $pagecounter = $page + 1;
315 $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
316 if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
317 else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
319 while ($rstest && $rstest->EOF && $pagecounter>0) {
322 $pagecounteroffset = $nrows * ($pagecounter - 1);
324 if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
325 else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
327 if ($rstest) $rstest->Close();
329 if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
330 $page = $pagecounter;
331 if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
332 //... page, that is, the recordset has only 1 page.
335 // We get the data we want
336 $offset = $nrows * ($page-1);
337 if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
338 else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
340 // Before returning the RecordSet, we set the pagination properties we need
342 $rsreturn->rowsPerPage = $nrows;
343 $rsreturn->AbsolutePage($page);
344 $rsreturn->AtFirstPage($atfirstpage);
345 $rsreturn->AtLastPage($atlastpage);
350 function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
353 printf(ADODB_BAD_RS,'GetUpdateSQL');
357 $fieldUpdatedCount = 0;
358 $arrFields = _array_change_key_case($arrFields);
360 $hasnumeric = isset($rs->fields[0]);
363 // Loop through all of the fields in the recordset
364 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
365 // Get the field from the recordset
366 $field = $rs->FetchField($i);
368 // If the recordset field is one
369 // of the fields passed in then process.
370 $upperfname = strtoupper($field->name);
371 if (adodb_key_exists($upperfname,$arrFields)) {
373 // If the existing field value in the recordset
374 // is different from the value passed in then
375 // go ahead and append the field name and new value to
378 if ($hasnumeric) $val = $rs->fields[$i];
379 else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
380 else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name];
381 else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)];
385 if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
386 // Set the counter for the number of fields that will be updated.
387 $fieldUpdatedCount++;
389 // Based on the datatype of the field
390 // Format the value properly for the database
391 $type = $rs->MetaType($field->type);
393 // is_null requires php 4.0.4
394 if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) ||
395 $arrFields[$upperfname] === 'null') {
396 $setFields .= $field->name . " = null, ";
398 if ($type == 'null') {
401 //we do this so each driver can customize the sql for
402 //DB specific column types.
403 //Oracle needs BLOB types to be handled with a returning clause
404 //postgres has special needs as well
405 $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname,
406 $arrFields, $magicq);
412 // If there were any modified fields then build the rest of the update query.
413 if ($fieldUpdatedCount > 0 || $forceUpdate) {
414 // Get the table name from the existing query.
415 preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
417 // Get the full where clause excluding the word "WHERE" from
418 // the existing query.
419 preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
422 // not a good hack, improvements?
424 preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
426 $whereClause = array(false,false);
429 $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
431 $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2);
432 if (strlen($whereClause[1]) > 0)
433 $sql .= ' WHERE '.$whereClause[1];
442 function adodb_key_exists($key, &$arr)
444 if (!defined('ADODB_FORCE_NULLS')) {
445 // the following is the old behaviour where null or empty fields are ignored
446 return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
449 if (isset($arr[$key])) return true;
451 if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
456 * There is a special case of this function for the oci8 driver.
457 * The proper way to handle an insert w/ a blob in oracle requires
458 * a returning clause with bind variables and a descriptor blob.
462 function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
468 $arrFields = _array_change_key_case($arrFields);
469 $fieldInsertedCount = 0;
471 if (is_string($rs)) {
472 //ok we have a table name
473 //try and get the column info ourself.
476 //we need an object for the recordSet
477 //because we have to call MetaType.
478 //php can't do a $rsclass::MetaType()
479 $rsclass = $zthis->rsPrefix.$zthis->databaseType;
480 $recordSet =& new $rsclass(-1,$zthis->fetchMode);
481 $recordSet->connection = &$zthis;
483 $columns = $zthis->MetaColumns( $tableName );
484 } else if (is_subclass_of($rs, 'adorecordset')) {
485 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
486 $columns[] = $rs->FetchField($i);
490 printf(ADODB_BAD_RS,'GetInsertSQL');
494 // Loop through all of the fields in the recordset
495 foreach( $columns as $field ) {
496 $upperfname = strtoupper($field->name);
497 if (adodb_key_exists($upperfname,$arrFields)) {
499 // Set the counter for the number of fields that will be inserted.
500 $fieldInsertedCount++;
502 // Get the name of the fields to insert
503 $fields .= $field->name . ", ";
505 $type = $recordSet->MetaType($field->type);
507 if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) ||
508 $arrFields[$upperfname] === 'null') {
511 //we do this so each driver can customize the sql for
512 //DB specific column types.
513 //Oracle needs BLOB types to be handled with a returning clause
514 //postgres has special needs as well
515 $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname,
516 $arrFields, $magicq);
522 // If there were any inserted fields then build the rest of the insert query.
523 if ($fieldInsertedCount <= 0) return false;
525 // Get the table name from the existing query.
527 preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
528 $tableName = $tableName[1];
531 // Strip off the comma and space on the end of both the fields
533 $fields = substr($fields, 0, -2);
534 $values = substr($values, 0, -2);
536 // Append the fields and their values to the insert query.
537 return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
542 * This private method is used to help construct
543 * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
544 * It handles the string construction of 1 column -> sql string based on
545 * the column type. We want to do 'safe' handling of BLOBs
547 * @param string the type of sql we are trying to create
549 * @param string column data type from the db::MetaType() method
550 * @param string the column name
551 * @param array the column value
556 function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $arrFields, $magicq)
560 // Based on the datatype of the field
561 // Format the value properly for the database
564 //in order to handle Blobs correctly, we need
565 //to do some magic for Oracle
567 //we need to create a new descriptor to handle
569 if (!empty($zthis->hasReturningInto)) {
570 if ($action == 'I') {
571 $sql = 'empty_blob(), ';
573 $sql = $fname. '=empty_blob(), ';
575 //add the variable to the returning clause array
576 //so the user can build this later in
577 //case they want to add more to it
578 $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
580 //this is to maintain compatibility
581 //with older adodb versions.
582 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
587 //we need to do some more magic here for long variables
588 //to handle these correctly in oracle.
590 //create a safe bind var name
591 //to avoid conflicts w/ dupes.
592 if (!empty($zthis->hasReturningInto)) {
593 if ($action == 'I') {
594 $sql = ':xx'.$fname.'xx, ';
596 $sql = $fname.'=:xx'.$fname.'xx, ';
598 //add the variable to the returning clause array
599 //so the user can build this later in
600 //case they want to add more to it
601 $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
603 //this is to maintain compatibility
604 //with older adodb versions.
605 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
610 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
617 function _adodb_column_sql(&$zthis, $action, $type, $fname, $arrFields, $magicq, $recurse=true)
621 switch($zthis->dataProvider) {
623 if ($type == 'L') $type = 'C';
626 return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $arrFields, $magicq);
637 if ($action == 'I') {
638 $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", ";
640 $sql .= $fname . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", ";
645 if ($action == 'I') {
646 $sql = $zthis->DBDate($arrFields[$fname]) . ", ";
648 $sql .= $fname . "=" . $zthis->DBDate($arrFields[$fname]) . ", ";
653 if ($action == 'I') {
654 $sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
656 $sql .= $fname . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
661 $val = $arrFields[$fname];
662 if (empty($val)) $val = '0';
665 if ($action == 'I') {
668 $sql .= $fname . "=" . $val . ", ";