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.
16 // Force key to upper.
17 // See also http://www.php.net/manual/en/function.array-change-key-case.php
18 function _array_change_key_case($an_array)
20 if (is_array($an_array)) {
21 foreach($an_array as $key=>$value)
22 $new_array[strtoupper($key)] = $value;
30 function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
32 if (count($fieldArray) == 0) return 0;
36 if (!is_array($keyCol)) {
37 $keyCol = array($keyCol);
39 foreach($fieldArray as $k => $v) {
40 if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {
41 $v = $zthis->qstr($v);
44 if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
54 foreach ($keyCol as $v) {
55 if ($where) $where .= " and $v=$fieldArray[$v]";
56 else $where = "$v=$fieldArray[$v]";
59 if ($uSet && $where) {
60 $update = "UPDATE $table SET $uSet WHERE $where";
62 $rs = $zthis->Execute($update);
64 if ($zthis->poorAffectedRows) {
66 The Select count(*) wipes out any errors that the update would have returned.
67 http://phplens.com/lens/lensforum/msgs.php?id=5696
69 if ($zthis->ErrorNo()<>0) return 0;
71 # affected_rows == 0 if update field values identical to old values
72 # for mysql - which is silly.
74 $cnt = $zthis->GetOne("select count(*) from $table where $where");
75 if ($cnt > 0) return 1; // record already exists
77 if (($zthis->Affected_Rows()>0)) return 1;
80 // print "<p>Error=".$this->ErrorNo().'<p>';
82 foreach($fieldArray as $k => $v) {
83 if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
94 $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
95 $rs = $zthis->Execute($insert);
99 // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
100 function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
101 $size=0, $selectAttr='',$compareFields0=true)
105 if ($multiple or is_array($defstr)) {
106 if ($size==0) $size=5;
107 $attr = " multiple size=$size";
108 if (!strpos($name,'[]')) $name .= '[]';
109 } elseif ($size) $attr = " size=$size";
112 $s = "<select name=\"$name\"$attr $selectAttr>";
114 if (is_string($blank1stItem)) {
115 $barr = explode(':',$blank1stItem);
116 if (sizeof($barr) == 1) $barr[] = '';
117 $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
118 } else $s .= "\n<option></option>";
120 if ($zthis->FieldCount() > 1) $hasvalue=true;
121 else $compareFields0 = true;
124 while(!$zthis->EOF) {
125 $zval = rtrim(reset($zthis->fields));
126 if (sizeof($zthis->fields) > 1) {
127 if (isset($zthis->fields[1]))
128 $zval2 = rtrim($zthis->fields[1]);
130 $zval2 = rtrim(next($zthis->fields));
132 $selected = ($compareFields0) ? $zval : $zval2;
134 if ($blank1stItem && $zval=="") {
139 $value = ' value="'.htmlspecialchars($zval2).'"';
141 if (is_array($defstr)) {
143 if (in_array($selected,$defstr))
144 $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
146 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
149 if (strcasecmp($selected,$defstr)==0)
150 $s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
152 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
157 return $s ."\n</select>\n";
161 Count the number of records this sql statement will return by using
162 query rewriting techniques...
164 Does not work with UNIONs.
166 function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
170 if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
171 // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
172 // but this is only supported by oracle and postgresql...
173 if ($zthis->dataProvider == 'oci8') {
175 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
176 $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
178 } elseif ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') {
180 $info = $zthis->ServerInfo();
181 if (substr($info['version'],0,3) >= 7.1) { // good till version 999
182 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
183 $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
187 // now replace SELECT ... FROM with SELECT COUNT(*) FROM
189 $rewritesql = preg_replace(
190 '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
192 // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
193 // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
194 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
197 if (isset($rewritesql) && $rewritesql != $sql) {
199 // we only use half the time of secs2cache because the count can quickly
200 // become inaccurate if new records are added
201 $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
204 $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
206 if ($qryRecs !== false) return $qryRecs;
209 //--------------------------------------------
210 // query rewrite failed - so try slower way...
212 // strip off unneeded ORDER BY
213 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
214 $rstest = &$zthis->Execute($rewritesql,$inputarr);
216 $qryRecs = $rstest->RecordCount();
217 if ($qryRecs == -1) {
218 global $ADODB_EXTENSION;
219 // some databases will return -1 on MoveLast() - change to MoveNext()
220 if ($ADODB_EXTENSION) {
221 while(!$rstest->EOF) {
222 adodb_movenext($rstest);
225 while(!$rstest->EOF) {
229 $qryRecs = $rstest->_currentRow;
232 if ($qryRecs == -1) return 0;
239 Code originally from "Cornel G" <conyg@fx.ro>
241 This code will not work with SQL that has UNION in it
243 Also if you are using CachePageExecute(), there is a strong possibility that
244 data will get out of synch. use CachePageExecute() only with tables that
247 function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
248 $inputarr=false, $secs2cache=0)
250 $atfirstpage = false;
254 // If an invalid nrows is supplied,
255 // we assume a default value of 10 rows per page
256 if (!isset($nrows) || $nrows <= 0) $nrows = 10;
258 $qryRecs = false; //count records for no offset
260 $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
261 $lastpageno = (int) ceil($qryRecs / $nrows);
262 $zthis->_maxRecordCount = $qryRecs;
264 // If page number <= 1, then we are at the first page
265 if (!isset($page) || $page <= 1) {
270 // ***** Here we check whether $page is the last page or
271 // whether we are trying to retrieve
272 // a page number greater than the last page number.
273 if ($page >= $lastpageno) {
278 // We get the data we want
279 $offset = $nrows * ($page-1);
281 $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
283 $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
285 // Before returning the RecordSet, we set the pagination properties we need
287 $rsreturn->_maxRecordCount = $qryRecs;
288 $rsreturn->rowsPerPage = $nrows;
289 $rsreturn->AbsolutePage($page);
290 $rsreturn->AtFirstPage($atfirstpage);
291 $rsreturn->AtLastPage($atlastpage);
292 $rsreturn->LastPageNo($lastpageno);
297 // Iván Oliva version
298 function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
301 $atfirstpage = false;
304 if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page
308 if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
310 // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
311 // the last page number.
312 $pagecounter = $page + 1;
313 $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
314 if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
315 else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
317 while ($rstest && $rstest->EOF && $pagecounter>0) {
320 $pagecounteroffset = $nrows * ($pagecounter - 1);
322 if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
323 else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
325 if ($rstest) $rstest->Close();
327 if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
328 $page = $pagecounter;
329 if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
330 //... page, that is, the recordset has only 1 page.
333 // We get the data we want
334 $offset = $nrows * ($page-1);
335 if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
336 else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
338 // Before returning the RecordSet, we set the pagination properties we need
340 $rsreturn->rowsPerPage = $nrows;
341 $rsreturn->AbsolutePage($page);
342 $rsreturn->AtFirstPage($atfirstpage);
343 $rsreturn->AtLastPage($atlastpage);
348 function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
351 printf(ADODB_BAD_RS,'GetUpdateSQL');
355 $fieldUpdatedCount = 0;
356 $arrFields = _array_change_key_case($arrFields);
358 $hasnumeric = isset($rs->fields[0]);
361 // Loop through all of the fields in the recordset
362 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
363 // Get the field from the recordset
364 $field = $rs->FetchField($i);
366 // If the recordset field is one
367 // of the fields passed in then process.
368 $upperfname = strtoupper($field->name);
369 if (adodb_key_exists($upperfname,$arrFields)) {
371 // If the existing field value in the recordset
372 // is different from the value passed in then
373 // go ahead and append the field name and new value to
376 if ($hasnumeric) $val = $rs->fields[$i];
377 else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
378 else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name];
379 else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)];
382 if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
383 // Set the counter for the number of fields that will be updated.
384 $fieldUpdatedCount++;
386 // Based on the datatype of the field
387 // Format the value properly for the database
388 $type = $rs->MetaType($field->type);
390 // is_null requires php 4.0.4
391 if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) ||
392 $arrFields[$upperfname] === 'null') {
393 $setFields .= $field->name . " = null, ";
395 if ($type == 'null') {
398 //we do this so each driver can customize the sql for
399 //DB specific column types.
400 //Oracle needs BLOB types to be handled with a returning clause
401 //postgres has special needs as well
402 $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname,
403 $arrFields, $magicq);
409 // If there were any modified fields then build the rest of the update query.
410 if ($fieldUpdatedCount > 0 || $forceUpdate) {
411 // Get the table name from the existing query.
412 preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
414 // Get the full where clause excluding the word "WHERE" from
415 // the existing query.
416 preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
419 // not a good hack, improvements?
421 preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
423 $whereClause = array(false,false);
426 $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
428 $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2);
429 if (strlen($whereClause[1]) > 0)
430 $sql .= ' WHERE '.$whereClause[1];
439 function adodb_key_exists($key, &$arr)
441 if (!defined('ADODB_FORCE_NULLS')) {
442 // the following is the old behaviour where null or empty fields are ignored
443 return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
446 if (isset($arr[$key])) return true;
448 if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
453 * There is a special case of this function for the oci8 driver.
454 * The proper way to handle an insert w/ a blob in oracle requires
455 * a returning clause with bind variables and a descriptor blob.
459 function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
465 $arrFields = _array_change_key_case($arrFields);
466 $fieldInsertedCount = 0;
468 if (is_string($rs)) {
469 //ok we have a table name
470 //try and get the column info ourself.
473 //we need an object for the recordSet
474 //because we have to call MetaType.
475 //php can't do a $rsclass::MetaType()
476 $rsclass = $zthis->rsPrefix.$zthis->databaseType;
477 $recordSet =& new $rsclass(-1,$zthis->fetchMode);
478 $recordSet->connection = &$zthis;
480 $columns = $zthis->MetaColumns( $tableName );
481 } elseif (is_subclass_of($rs, 'adorecordset')) {
482 for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
483 $columns[] = $rs->FetchField($i);
487 printf(ADODB_BAD_RS,'GetInsertSQL');
491 // Loop through all of the fields in the recordset
492 foreach( $columns as $field ) {
493 $upperfname = strtoupper($field->name);
494 if (adodb_key_exists($upperfname,$arrFields)) {
496 // Set the counter for the number of fields that will be inserted.
497 $fieldInsertedCount++;
499 // Get the name of the fields to insert
500 $fields .= $field->name . ", ";
502 $type = $recordSet->MetaType($field->type);
504 if ((defined('ADODB_FORCE_NULLS') && is_null($arrFields[$upperfname])) ||
505 $arrFields[$upperfname] === 'null') {
508 //we do this so each driver can customize the sql for
509 //DB specific column types.
510 //Oracle needs BLOB types to be handled with a returning clause
511 //postgres has special needs as well
512 $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname,
513 $arrFields, $magicq);
519 // If there were any inserted fields then build the rest of the insert query.
520 if ($fieldInsertedCount <= 0) return false;
522 // Get the table name from the existing query.
524 preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
525 $tableName = $tableName[1];
528 // Strip off the comma and space on the end of both the fields
530 $fields = substr($fields, 0, -2);
531 $values = substr($values, 0, -2);
533 // Append the fields and their values to the insert query.
534 return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
539 * This private method is used to help construct
540 * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
541 * It handles the string construction of 1 column -> sql string based on
542 * the column type. We want to do 'safe' handling of BLOBs
544 * @param string the type of sql we are trying to create
546 * @param string column data type from the db::MetaType() method
547 * @param string the column name
548 * @param array the column value
553 function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $arrFields, $magicq)
557 // Based on the datatype of the field
558 // Format the value properly for the database
561 //in order to handle Blobs correctly, we need
562 //to do some magic for Oracle
564 //we need to create a new descriptor to handle
566 if (!empty($zthis->hasReturningInto)) {
567 if ($action == 'I') {
568 $sql = 'empty_blob(), ';
570 $sql = $fname. '=empty_blob(), ';
572 //add the variable to the returning clause array
573 //so the user can build this later in
574 //case they want to add more to it
575 $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
577 //this is to maintain compatibility
578 //with older adodb versions.
579 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
584 //we need to do some more magic here for long variables
585 //to handle these correctly in oracle.
587 //create a safe bind var name
588 //to avoid conflicts w/ dupes.
589 if (!empty($zthis->hasReturningInto)) {
590 if ($action == 'I') {
591 $sql = ':xx'.$fname.'xx, ';
593 $sql = $fname.'=:xx'.$fname.'xx, ';
595 //add the variable to the returning clause array
596 //so the user can build this later in
597 //case they want to add more to it
598 $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
600 //this is to maintain compatibility
601 //with older adodb versions.
602 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
607 $sql = _adodb_column_sql($zthis, $action, $type, $fname, $arrFields, $magicq,false);
614 function _adodb_column_sql(&$zthis, $action, $type, $fname, $arrFields, $magicq, $recurse=true)
618 switch($zthis->dataProvider) {
620 if ($type == 'L') $type = 'C';
623 return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $arrFields, $magicq);
634 if ($action == 'I') {
635 $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", ";
637 $sql .= $fname . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", ";
642 if ($action == 'I') {
643 $sql = $zthis->DBDate($arrFields[$fname]) . ", ";
645 $sql .= $fname . "=" . $zthis->DBDate($arrFields[$fname]) . ", ";
650 if ($action == 'I') {
651 $sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
653 $sql .= $fname . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
658 $val = $arrFields[$fname];
659 if (empty($val)) $val = '0';
662 if ($action == 'I') {
665 $sql .= $fname . "=" . $val . ", ";