<?php
/*
-@version V5.19 23-Apr-2014 (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+@version v5.20.1 06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
Latest version is available at http://adodb.sourceforge.net
Released under both BSD license and Lesser GPL library license.
foreach($_ADODB_ACTIVE_DBS as $k => $d) {
if (PHP_VERSION >= 5) {
- if ($d->db === $db) return $k;
+ if ($d->db === $db) {
+ return $k;
+ }
} else {
- if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
+ if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) {
return $k;
+ }
}
}
$obj->db = $db;
$obj->tables = array();
- if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
-
+ if ($index == false) {
+ $index = sizeof($_ADODB_ACTIVE_DBS);
+ }
$_ADODB_ACTIVE_DBS[$index] = $obj;
static function UseDefaultValues($bool=null)
{
global $ADODB_ACTIVE_DEFVALS;
- if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+ if (isset($bool)) {
+ $ADODB_ACTIVE_DEFVALS = $bool;
+ }
return $ADODB_ACTIVE_DEFVALS;
}
}
if (!$table) {
- if (!empty($this->_table)) $table = $this->_table;
+ if (!empty($this->_table)) {
+ $table = $this->_table;
+ }
else $table = $this->_pluralize(get_class($this));
}
$this->foreignName = strtolower(get_class($this)); // CFR: default foreign name
if ($db) {
$this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
} else if (!isset($this->_dbat)) {
- if (sizeof($_ADODB_ACTIVE_DBS) == 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
+ if (sizeof($_ADODB_ACTIVE_DBS) == 0) {
+ $this->Error(
+ "No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",
+ 'ADODB_Active_Record::__constructor'
+ );
+ }
end($_ADODB_ACTIVE_DBS);
$this->_dbat = key($_ADODB_ACTIVE_DBS);
}
function _pluralize($table)
{
- if (!ADODB_Active_Record::$_changeNames) return $table;
+ if (!ADODB_Active_Record::$_changeNames) {
+ return $table;
+ }
$ut = strtoupper($table);
$len = strlen($table);
case 'X':
return $table.'es';
case 'H':
- if ($lastc2 == 'CH' || $lastc2 == 'SH')
+ if ($lastc2 == 'CH' || $lastc2 == 'SH') {
return $table.'es';
+ }
default:
return $table.'s';
}
function _singularize($tables)
{
- if (!ADODB_Active_Record::$_changeNames) return $table;
+ if (!ADODB_Active_Record::$_changeNames) {
+ return $table;
+ }
$ut = strtoupper($tables);
$len = strlen($tables);
- if($ut[$len-1] != 'S')
+ if($ut[$len-1] != 'S') {
return $tables; // I know...forget oxen
- if($ut[$len-2] != 'E')
+ }
+ if($ut[$len-2] != 'E') {
return substr($tables, 0, $len-1);
- switch($ut[$len-3])
- {
+ }
+ switch($ut[$len-3]) {
case 'S':
case 'X':
return substr($tables, 0, $len-2);
case 'I':
return substr($tables, 0, $len-3) . 'y';
case 'H';
- if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
+ if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
return substr($tables, 0, $len-2);
+ }
default:
return substr($tables, 0, $len-1); // ?
}
// use when you don't want ADOdb to auto-pluralize tablename
static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
{
- if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
+ if (!is_array($tablePKey)) {
+ $tablePKey = array($tablePKey);
+ }
$ar = new ADODB_Active_Record($table,$tablePKey);
$ar->hasMany($foreignRef, $foreignKey, $foreignClass);
}
static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
{
- if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
+ if (!is_array($tablePKey)) {
+ $tablePKey = array($tablePKey);
+ }
$ar = new ADOdb_Active_Record($table, $tablePKey);
$ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
}
{
$extras = array();
$table = $this->TableInfo();
- if ($limit >= 0) $extras['limit'] = $limit;
- if ($offset >= 0) $extras['offset'] = $offset;
+ if ($limit >= 0) {
+ $extras['limit'] = $limit;
+ }
+ if ($offset >= 0) {
+ $extras['offset'] = $offset;
+ }
- if (strlen($whereOrderBy))
- if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
- if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
- $whereOrderBy = 'AND '.$whereOrderBy;
+ if (strlen($whereOrderBy)) {
+ if (!preg_match('/^[ \n\r]*AND/i', $whereOrderBy)) {
+ if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i', $whereOrderBy)) {
+ $whereOrderBy = 'AND ' . $whereOrderBy;
+ }
+ }
+ }
- if(!empty($table->_belongsTo[$name]))
- {
+ if(!empty($table->_belongsTo[$name])) {
$obj = $table->_belongsTo[$name];
$columnName = $obj->foreignKey;
- if(empty($this->$columnName))
+ if(empty($this->$columnName)) {
$this->$name = null;
- else
- {
- if ($obj->parentKey) $key = $obj->parentKey;
- else $key = reset($table->keys);
+ }
+ else {
+ if ($obj->parentKey) {
+ $key = $obj->parentKey;
+ }
+ else {
+ $key = reset($table->keys);
+ }
$arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
if ($arrayOfOne) {
}
}
}
- if(!empty($table->_hasMany[$name]))
- {
+ if(!empty($table->_hasMany[$name])) {
$obj = $table->_hasMany[$name];
$key = reset($table->keys);
$id = @$this->$key;
$id = $db->qstr($id);
}
$objs = $obj->Find($obj->foreignKey.'='.$id. ' '.$whereOrderBy,false,false,$extras);
- if (!$objs) $objs = array();
+ if (!$objs) {
+ $objs = array();
+ }
$this->$name = $objs;
return $objs;
}
$acttab = $tables[$tableat];
foreach($acttab->flds as $name => $fld) {
- if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
- $this->$name = $fld->default_value;
- else
- $this->$name = null;
+ if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
+ $this->$name = $fld->default_value;
+ }
+ else {
+ $this->$name = null;
+ }
}
return;
}
// ideally, you should cache at least 32 secs
foreach($acttab->flds as $name => $fld) {
- if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
+ if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
$this->$name = $fld->default_value;
- else
+ }
+ else {
$this->$name = null;
+ }
}
$activedb->tables[$table] = $acttab;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
- if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
+ if ($db->fetchMode !== false) {
+ $savem = $db->SetFetchMode(false);
+ }
$cols = $db->MetaColumns($table);
- if (isset($savem)) $db->SetFetchMode($savem);
+ if (isset($savem)) {
+ $db->SetFetchMode($savem);
+ }
$ADODB_FETCH_MODE = $save;
if (!$cols) {
if (isset($fld->primary_key)) {
$pkeys = array();
foreach($cols as $name => $fld) {
- if (!empty($fld->primary_key)) $pkeys[] = $name;
+ if (!empty($fld->primary_key)) {
+ $pkeys[] = $name;
+ }
}
} else
$pkeys = $this->GetPrimaryKeys($db, $table);
case 0:
foreach($cols as $name => $fldobj) {
$name = strtolower($name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
foreach($cols as $name => $fldobj) {
$name = strtoupper($name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($cols as $name => $fldobj) {
$name = ($fldobj->name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
$activetab->_created = time();
$s = serialize($activetab);
- if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+ if (!function_exists('adodb_write_file')) {
+ include(ADODB_DIR.'/adodb-csvlib.inc.php');
+ }
adodb_write_file($fname,$s);
}
if (isset($activedb->tables[$table])) {
$oldtab = $activedb->tables[$table];
- if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
- if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
+ if ($oldtab) {
+ $activetab->_belongsTo = $oldtab->_belongsTo;
+ $activetab->_hasMany = $oldtab->_hasMany;
+ }
}
$activedb->tables[$table] = $activetab;
}
$fn = get_class($this).'::'.$fn;
$this->_lasterr = $fn.': '.$err;
- if ($this->_dbat < 0) $db = false;
+ if ($this->_dbat < 0) {
+ $db = false;
+ }
else {
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$db = $activedb->db;
}
if (function_exists('adodb_throw')) {
- if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
- else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
- } else
- if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
+ if (!$db) {
+ adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
+ }
+ else {
+ adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
+ }
+ } else {
+ if (!$db || $db->debug) {
+ ADOConnection::outp($this->_lasterr);
+ }
+ }
}
function ErrorMsg()
{
if (!function_exists('adodb_throw')) {
- if ($this->_dbat < 0) $db = false;
- else $db = $this->DB();
+ if ($this->_dbat < 0) {
+ $db = false;
+ }
+ else {
+ $db = $this->DB();
+ }
// last error could be database error too
- if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+ if ($db && $db->ErrorMsg()) {
+ return $db->ErrorMsg();
+ }
}
return $this->_lasterr;
}
function ErrorNo()
{
- if ($this->_dbat < 0) return -9999; // no database connection...
+ if ($this->_dbat < 0) {
+ return -9999; // no database connection...
+ }
$db = $this->DB();
return (int) $db->ErrorNo();
// So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
function Reload()
{
- $db =& $this->DB(); if (!$db) return false;
- $table =& $this->TableInfo();
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
+ $table = $this->TableInfo();
$where = $this->GenWhere($db, $table);
return($this->Load($where));
}
$table = $this->TableInfo();
if ($ACTIVE_RECORD_SAFETY && sizeof($table->flds) != sizeof($row)) {
- # <AP>
- $bad_size = TRUE;
- if (sizeof($row) == 2 * sizeof($table->flds)) {
- // Only keep string keys
- $keys = array_filter(array_keys($row), 'is_string');
- if (sizeof($keys) == sizeof($table->flds))
- $bad_size = FALSE;
- }
- if ($bad_size) {
+ # <AP>
+ $bad_size = TRUE;
+ if (sizeof($row) == 2 * sizeof($table->flds)) {
+ // Only keep string keys
+ $keys = array_filter(array_keys($row), 'is_string');
+ if (sizeof($keys) == sizeof($table->flds)) {
+ $bad_size = FALSE;
+ }
+ }
+ if ($bad_size) {
$this->Error("Table structure of $this->_table has changed","Load");
return false;
}
- # </AP>
+ # </AP>
}
- else
+ else
$keys = array_keys($row);
- # <AP>
- reset($keys);
- $this->_original = array();
+ # <AP>
+ reset($keys);
+ $this->_original = array();
foreach($table->flds as $name=>$fld) {
- $value = $row[current($keys)];
+ $value = $row[current($keys)];
$this->$name = $value;
- $this->_original[] = $value;
- next($keys);
+ $this->_original[] = $value;
+ next($keys);
}
- # </AP>
+ # </AP>
return true;
}
// get last inserted id for INSERT
function LastInsertID(&$db,$fieldname)
{
- if ($db->hasInsertID)
+ if ($db->hasInsertID) {
$val = $db->Insert_ID($this->_table,$fieldname);
- else
+ }
+ else {
$val = false;
+ }
if (is_null($val) || $val === false) {
// this might not work reliably in multi-user environment
{
switch($t) {
case 'L':
- if (strpos($db->databaseType,'postgres') !== false) return $db->qstr($val);
+ if (strpos($db->databaseType,'postgres') !== false) {
+ return $db->qstr($val);
+ }
case 'D':
case 'T':
- if (empty($val)) return 'null';
-
+ if (empty($val)) {
+ return 'null';
+ }
case 'B':
case 'N':
case 'C':
case 'X':
- if (is_null($val)) return 'null';
+ if (is_null($val)) {
+ return 'null';
+ }
if (strlen($val)>0 &&
- (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+ (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")
+ ) {
return $db->qstr($val);
break;
}
function _QName($n,$db=false)
{
- if (!ADODB_Active_Record::$_quoteNames) return $n;
- if (!$db) $db = $this->DB(); if (!$db) return false;
+ if (!ADODB_Active_Record::$_quoteNames) {
+ return $n;
+ }
+ if (!$db) {
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
+ }
return $db->nameQuote.$n.$db->nameQuote;
}
{
global $ADODB_FETCH_MODE;
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$this->_where = $where;
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
- if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
+ if ($db->fetchMode !== false) {
+ $savem = $db->SetFetchMode(false);
+ }
$qry = "select * from ".$this->_table;
if($where) {
$qry .= ' WHERE '.$where;
}
- if ($lock) $qry .= $this->lockMode;
+ if ($lock) {
+ $qry .= $this->lockMode;
+ }
$row = $db->GetRow($qry,$bindarr);
- if (isset($savem)) $db->SetFetchMode($savem);
+ if (isset($savem)) {
+ $db->SetFetchMode($savem);
+ }
$ADODB_FETCH_MODE = $save;
return $this->Set($row);
# see http://phplens.com/lens/lensforum/msgs.php?id=17795
function Reset()
{
- $this->_where=null;
- $this->_saved = false;
- $this->_lasterr = false;
- $this->_original = false;
- $vars=get_object_vars($this);
- foreach($vars as $k=>$v){
- if(substr($k,0,1)!=='_'){
- $this->{$k}=null;
- }
- }
- $this->foreignName=strtolower(get_class($this));
- return true;
- }
+ $this->_where=null;
+ $this->_saved = false;
+ $this->_lasterr = false;
+ $this->_original = false;
+ $vars=get_object_vars($this);
+ foreach($vars as $k=>$v){
+ if(substr($k,0,1)!=='_'){
+ $this->{$k}=null;
+ }
+ }
+ $this->foreignName=strtolower(get_class($this));
+ return true;
+ }
// false on error
function Save()
{
- if ($this->_saved) $ok = $this->Update();
- else $ok = $this->Insert();
+ if ($this->_saved) {
+ $ok = $this->Update();
+ }
+ else {
+ $ok = $this->Insert();
+ }
return $ok;
}
// false on error
function Insert()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$cnt = 0;
$table = $this->TableInfo();
function Delete()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$where = $this->GenWhere($db,$table);
// returns an array of active record objects
function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
{
- $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+ $db = $this->DB();
+ if (!$db || empty($this->_table)) {
+ return false;
+ }
$arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
return $arr;
}
{
global $ADODB_ASSOC_CASE;
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$pkey = $table->keys;
/*
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
- if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+ if (isset($fld->default_value) && strlen($fld->default_value)) {
+ continue;
+ }
else {
$this->Error("Cannot update null into $name","Replace");
return false;
}
}*/
if (is_null($val) && !empty($fld->auto_increment)) {
- continue;
- }
+ continue;
+ }
- if (is_array($val)) continue;
+ if (is_array($val)) {
+ continue;
+ }
$t = $db->MetaType($fld->type);
$arr[$name] = $this->doquote($db,$val,$t);
$valarr[] = $val;
}
- if (!is_array($pkey)) $pkey = array($pkey);
-
+ if (!is_array($pkey)) {
+ $pkey = array($pkey);
+ }
- if ($ADODB_ASSOC_CASE == 0)
+ if ($ADODB_ASSOC_CASE == 0) {
foreach($pkey as $k => $v)
$pkey[$k] = strtolower($v);
- elseif ($ADODB_ASSOC_CASE == 1)
- foreach($pkey as $k => $v)
+ }
+ elseif ($ADODB_ASSOC_CASE == 1) {
+ foreach($pkey as $k => $v) {
$pkey[$k] = strtoupper($v);
+ }
+ }
$ok = $db->Replace($this->_table,$arr,$pkey);
if ($ok) {
// returns 0 on error, 1 on update, -1 if no change in data (no update)
function Update()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$where = $this->GenWhere($db, $table);
$val = $this->$name;
$neworig[] = $val;
- if (isset($table->keys[$name]) || is_array($val))
+ if (isset($table->keys[$name]) || is_array($val)) {
continue;
+ }
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
- if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+ if (isset($fld->default_value) && strlen($fld->default_value)) {
+ continue;
+ }
else {
$this->Error("Cannot set field $name to NULL","Update");
return false;
}
}
- if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) continue;
+ if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) {
+ continue;
+ }
- if (is_null($this->_original[$i]) && is_null($val)) continue;
+ if (is_null($this->_original[$i]) && is_null($val)) {
+ continue;
+ }
$valarr[] = $val;
$pairs[] = $this->_QName($name,$db).'='.$db->Param($cnt);
}
- if (!$cnt) return -1;
+ if (!$cnt) {
+ return -1;
+ }
+
$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
$ok = $db->Execute($sql,$valarr);
if ($ok) {
function GetAttributeNames()
{
$table = $this->TableInfo();
- if (!$table) return false;
+ if (!$table) {
+ return false;
+ }
return array_keys($table->flds);
}
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$qry = "select * from ".$table;
- if (!empty($whereOrderBy))
+ if (!empty($whereOrderBy)) {
$qry .= ' WHERE '.$whereOrderBy;
- if(isset($extra['limit']))
- {
+ }
+ if(isset($extra['limit'])) {
$rows = false;
if(isset($extra['offset'])) {
$rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset'],$bindarr);
<?php
/*
-@version V5.19 23-Apr-2014 (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+@version v5.20.1 06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
Latest version is available at http://adodb.sourceforge.net
Released under both BSD license and Lesser GPL library license.
foreach($_ADODB_ACTIVE_DBS as $k => $d) {
if (PHP_VERSION >= 5) {
- if ($d->db === $db) return $k;
+ if ($d->db === $db) {
+ return $k;
+ }
} else {
- if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
+ if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) {
return $k;
+ }
}
}
static function UseDefaultValues($bool=null)
{
global $ADODB_ACTIVE_DEFVALS;
- if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+ if (isset($bool)) {
+ $ADODB_ACTIVE_DEFVALS = $bool;
+ }
return $ADODB_ACTIVE_DEFVALS;
}
$pkeyarr = false;
}
- if($table)
- {
+ if($table) {
// table argument exists. It is expected to be
// already plural form.
$this->_pTable = $table;
$this->_sTable = $this->_singularize($this->_pTable);
}
- else
- {
+ else {
// We will use current classname as table name.
// We need to pluralize it for the real table name.
$this->_sTable = strtolower(get_class($this));
$this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
- if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
+ if ($this->_dbat < 0) {
+ $this->Error(
+ "No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",
+ 'ADODB_Active_Record::__constructor'
+ );
+ }
$this->_tableat = $this->_table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
// but there was no way to ask it to do that.
$forceUpdate = (isset($options['refresh']) && true === $options['refresh']);
$this->UpdateActiveTable($pkeyarr, $forceUpdate);
- if(isset($options['new']) && true === $options['new'])
- {
+ if(isset($options['new']) && true === $options['new']) {
$table =& $this->TableInfo();
unset($table->_hasMany);
unset($table->_belongsTo);
function __wakeup()
{
- $class = get_class($this);
- new $class;
+ $class = get_class($this);
+ new $class;
}
// CFR: Constants found in Rails
function _pluralize($table)
{
- if (!ADODB_Active_Record::$_changeNames) return $table;
-
+ if (!ADODB_Active_Record::$_changeNames) {
+ return $table;
+ }
$ut = strtoupper($table);
- if(isset(self::$WeIsI[$ut]))
- {
+ if(isset(self::$WeIsI[$ut])) {
return $table;
}
- if(isset(self::$IrregularP[$ut]))
- {
+ if(isset(self::$IrregularP[$ut])) {
return self::$IrregularP[$ut];
}
$len = strlen($table);
$lastc = $ut[$len-1];
$lastc2 = substr($ut,$len-2);
switch ($lastc) {
- case 'S':
- return $table.'es';
- case 'Y':
- return substr($table,0,$len-1).'ies';
- case 'X':
- return $table.'es';
- case 'H':
- if ($lastc2 == 'CH' || $lastc2 == 'SH')
+ case 'S':
return $table.'es';
- default:
- return $table.'s';
+ case 'Y':
+ return substr($table,0,$len-1).'ies';
+ case 'X':
+ return $table.'es';
+ case 'H':
+ if ($lastc2 == 'CH' || $lastc2 == 'SH') {
+ return $table.'es';
+ }
+ default:
+ return $table.'s';
}
}
function _singularize($table)
{
- if (!ADODB_Active_Record::$_changeNames) return $table;
-
+ if (!ADODB_Active_Record::$_changeNames) {
+ return $table;
+ }
$ut = strtoupper($table);
- if(isset(self::$WeIsI[$ut]))
- {
+ if(isset(self::$WeIsI[$ut])) {
return $table;
}
- if(isset(self::$IrregularS[$ut]))
- {
+ if(isset(self::$IrregularS[$ut])) {
return self::$IrregularS[$ut];
}
$len = strlen($table);
- if($ut[$len-1] != 'S')
+ if($ut[$len-1] != 'S') {
return $table; // I know...forget oxen
- if($ut[$len-2] != 'E')
+ }
+ if($ut[$len-2] != 'E') {
return substr($table, 0, $len-1);
- switch($ut[$len-3])
- {
+ }
+ switch($ut[$len-3]) {
case 'S':
case 'X':
return substr($table, 0, $len-2);
case 'I':
return substr($table, 0, $len-3) . 'y';
case 'H';
- if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
+ if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
return substr($table, 0, $len-2);
+ }
default:
return substr($table, 0, $len-1); // ?
}
$ar->foreignKey = ($foreignKey) ? $foreignKey : strtolower(get_class($this)) . self::$_foreignSuffix;
$table =& $this->TableInfo();
- if(!isset($table->_hasMany[$foreignRef]))
- {
+ if(!isset($table->_hasMany[$foreignRef])) {
$table->_hasMany[$foreignRef] = $ar;
$table->updateColsCount();
}
$ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
$table =& $this->TableInfo();
- if(!isset($table->_belongsTo[$foreignRef]))
- {
+ if(!isset($table->_belongsTo[$foreignRef])) {
$table->_belongsTo[$foreignRef] = $ar;
$table->updateColsCount();
}
function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
{
$extras = array();
- if($offset >= 0) $extras['offset'] = $offset;
- if($limit >= 0) $extras['limit'] = $limit;
+ if($offset >= 0) {
+ $extras['offset'] = $offset;
+ }
+ if($limit >= 0) {
+ $extras['limit'] = $limit;
+ }
$table =& $this->TableInfo();
- if (strlen($whereOrderBy))
- if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
- if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
+ if (strlen($whereOrderBy)) {
+ if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy)) {
+ if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy)) {
$whereOrderBy = 'AND '.$whereOrderBy;
+ }
+ }
+ }
- if(!empty($table->_belongsTo[$name]))
- {
+ if(!empty($table->_belongsTo[$name])) {
$obj = $table->_belongsTo[$name];
$columnName = $obj->foreignKey;
- if(empty($this->$columnName))
+ if(empty($this->$columnName)) {
$this->$name = null;
- else
- {
- if(($k = reset($obj->TableInfo()->keys)))
+ }
+ else {
+ if(($k = reset($obj->TableInfo()->keys))) {
$belongsToId = $k;
- else
+ }
+ else {
$belongsToId = 'id';
+ }
$arrayOfOne =
$obj->Find(
}
return $this->$name;
}
- if(!empty($table->_hasMany[$name]))
- {
+ if(!empty($table->_hasMany[$name])) {
$obj = $table->_hasMany[$name];
- if(($k = reset($table->keys)))
+ if(($k = reset($table->keys))) {
$hasManyId = $k;
- else
+ }
+ else {
$hasManyId = 'id';
+ }
$this->$name =
$obj->Find(
$tobj = $tables[$tableat];
foreach($tobj->flds as $name => $fld) {
- if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
- $this->$name = $fld->default_value;
- else
- $this->$name = null;
+ if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
+ $this->$name = $fld->default_value;
+ }
+ else {
+ $this->$name = null;
+ }
}
return;
}
$activedb->tables[$table] = $acttab;
//if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
- return;
+ return;
} else if ($db->debug) {
ADOConnection::outp("Refreshing cached active record file: $fname");
}
$save = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
- if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
+ if ($db->fetchMode !== false) {
+ $savem = $db->SetFetchMode(false);
+ }
$cols = $db->MetaColumns($table);
- if (isset($savem)) $db->SetFetchMode($savem);
+ if (isset($savem)) {
+ $db->SetFetchMode($savem);
+ }
$ADODB_FETCH_MODE = $save;
if (!$cols) {
if (isset($fld->primary_key)) {
$pkeys = array();
foreach($cols as $name => $fld) {
- if (!empty($fld->primary_key)) $pkeys[] = $name;
+ if (!empty($fld->primary_key)) {
+ $pkeys[] = $name;
+ }
}
- } else
+ } else {
$pkeys = $this->GetPrimaryKeys($db, $table);
+ }
}
if (empty($pkeys)) {
$this->Error("No primary key found for table $table",'UpdateActiveTable');
case 0:
foreach($cols as $name => $fldobj) {
$name = strtolower($name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
foreach($cols as $name => $fldobj) {
$name = strtoupper($name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($cols as $name => $fldobj) {
$name = ($fldobj->name);
- if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
- $this->$name = $fldobj->default_value;
- else
+ if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+ $this->$name = $fldobj->default_value;
+ }
+ else {
$this->$name = null;
+ }
$attr[$name] = $fldobj;
}
foreach($pkeys as $k => $name) {
if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
$activetab->_created = time();
$s = serialize($activetab);
- if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+ if (!function_exists('adodb_write_file')) {
+ include(ADODB_DIR.'/adodb-csvlib.inc.php');
+ }
adodb_write_file($fname,$s);
}
if (isset($activedb->tables[$table])) {
$oldtab = $activedb->tables[$table];
- if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
- if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
+ if ($oldtab) {
+ $activetab->_belongsTo = $oldtab->_belongsTo;
+ $activetab->_hasMany = $oldtab->_hasMany;
+ }
}
$activedb->tables[$table] = $activetab;
}
$fn = get_class($this).'::'.$fn;
$this->_lasterr = $fn.': '.$err;
- if ($this->_dbat < 0) $db = false;
+ if ($this->_dbat < 0) {
+ $db = false;
+ }
else {
$activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
$db = $activedb->db;
}
if (function_exists('adodb_throw')) {
- if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
- else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
- } else
- if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
+ if (!$db) {
+ adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
+ }
+ else {
+ adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
+ }
+ } else {
+ if (!$db || $db->debug) {
+ ADOConnection::outp($this->_lasterr);
+ }
+ }
}
function ErrorMsg()
{
if (!function_exists('adodb_throw')) {
- if ($this->_dbat < 0) $db = false;
- else $db = $this->DB();
+ if ($this->_dbat < 0) {
+ $db = false;
+ }
+ else {
+ $db = $this->DB();
+ }
// last error could be database error too
- if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+ if ($db && $db->ErrorMsg()) {
+ return $db->ErrorMsg();
+ }
}
return $this->_lasterr;
}
function ErrorNo()
{
- if ($this->_dbat < 0) return -9999; // no database connection...
+ if ($this->_dbat < 0) {
+ return -9999; // no database connection...
+ }
$db = $this->DB();
return (int) $db->ErrorNo();
// So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
function Reload()
{
- $db =& $this->DB(); if (!$db) return false;
+ $db =& $this->DB();
+ if (!$db) {
+ return false;
+ }
$table =& $this->TableInfo();
$where = $this->GenWhere($db, $table);
return($this->Load($where));
$sizeofFlds = sizeof($table->flds);
$sizeofRow = sizeof($row);
if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
- # <AP>
- $bad_size = TRUE;
- if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
- // Only keep string keys
- $keys = array_filter(array_keys($row), 'is_string');
- if (sizeof($keys) == sizeof($table->flds))
- $bad_size = FALSE;
- }
- if ($bad_size) {
- $this->Error("Table structure of $this->_table has changed","Load");
- return false;
+ # <AP>
+ $bad_size = TRUE;
+ if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
+ // Only keep string keys
+ $keys = array_filter(array_keys($row), 'is_string');
+ if (sizeof($keys) == sizeof($table->flds)) {
+ $bad_size = FALSE;
+ }
+ }
+ if ($bad_size) {
+ $this->Error("Table structure of $this->_table has changed","Load");
+ return false;
+ }
+ # </AP>
}
- # </AP>
+ else {
+ $keys = array_keys($row);
}
- else
- $keys = array_keys($row);
- # <AP>
- reset($keys);
- $this->_original = array();
- foreach($table->flds as $name=>$fld)
- {
- $value = $row[current($keys)];
+
+ # <AP>
+ reset($keys);
+ $this->_original = array();
+ foreach($table->flds as $name=>$fld) {
+ $value = $row[current($keys)];
$this->$name = $value;
- $this->_original[] = $value;
- if(!next($keys)) break;
+ $this->_original[] = $value;
+ if(!next($keys)) {
+ break;
+ }
}
$table =& $this->TableInfo();
- foreach($table->_belongsTo as $foreignTable)
- {
+ foreach($table->_belongsTo as $foreignTable) {
$ft = $foreignTable->TableInfo();
$propertyName = $ft->name;
- foreach($ft->flds as $name=>$fld)
- {
+ foreach($ft->flds as $name=>$fld) {
$value = $row[current($keys)];
$foreignTable->$name = $value;
$foreignTable->_original[] = $value;
- if(!next($keys)) break;
+ if(!next($keys)) {
+ break;
+ }
}
}
- foreach($table->_hasMany as $foreignTable)
- {
+ foreach($table->_hasMany as $foreignTable) {
$ft = $foreignTable->TableInfo();
- foreach($ft->flds as $name=>$fld)
- {
+ foreach($ft->flds as $name=>$fld) {
$value = $row[current($keys)];
$foreignTable->$name = $value;
$foreignTable->_original[] = $value;
- if(!next($keys)) break;
+ if(!next($keys)) {
+ break;
+ }
}
}
- # </AP>
+ # </AP>
+
return true;
}
// get last inserted id for INSERT
function LastInsertID(&$db,$fieldname)
{
- if ($db->hasInsertID)
+ if ($db->hasInsertID) {
$val = $db->Insert_ID($this->_table,$fieldname);
- else
+ }
+ else {
$val = false;
+ }
if (is_null($val) || $val === false) {
// this might not work reliably in multi-user environment
switch($t) {
case 'D':
case 'T':
- if (empty($val)) return 'null';
-
+ if (empty($val)) {
+ return 'null';
+ }
case 'C':
case 'X':
- if (is_null($val)) return 'null';
-
+ if (is_null($val)) {
+ return 'null';
+ }
if (strlen($val)>0 &&
- (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+ (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")
+ ) {
return $db->qstr($val);
break;
}
function Load($where=null,$bindarr=false)
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$this->_where = $where;
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$qry = "select * from ".$this->_table;
$table =& $this->TableInfo();
- if(($k = reset($table->keys)))
+ if(($k = reset($table->keys))) {
$hasManyId = $k;
- else
+ }
+ else {
$hasManyId = 'id';
+ }
- foreach($table->_belongsTo as $foreignTable)
- {
- if(($k = reset($foreignTable->TableInfo()->keys)))
- {
+ foreach($table->_belongsTo as $foreignTable) {
+ if(($k = reset($foreignTable->TableInfo()->keys))) {
$belongsToId = $k;
}
- else
- {
+ else {
$belongsToId = 'id';
}
$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
$this->_table.'.'.$hasManyId.'='.
$foreignTable->_table.'.'.$foreignTable->foreignKey;
}
- if($where)
+ if($where) {
$qry .= ' WHERE '.$where;
+ }
// Simple case: no relations. Load row and return.
- if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
- {
+ if((count($table->_hasMany) + count($table->_belongsTo)) < 1) {
$row = $db->GetRow($qry,$bindarr);
- if(!$row)
+ if(!$row) {
return false;
+ }
$db->SetFetchMode($save);
return $this->Set($row);
}
// More complex case when relations have to be collated
$rows = $db->GetAll($qry,$bindarr);
- if(!$rows)
+ if(!$rows) {
return false;
+ }
$db->SetFetchMode($save);
- if(count($rows) < 1)
+ if(count($rows) < 1) {
return false;
+ }
$class = get_class($this);
$isFirstRow = true;
- if(($k = reset($this->TableInfo()->keys)))
+ if(($k = reset($this->TableInfo()->keys))) {
$myId = $k;
- else
+ }
+ else {
$myId = 'id';
+ }
$index = 0; $found = false;
/** @todo Improve by storing once and for all in table metadata */
/** @todo Also re-use info for hasManyId */
- foreach($this->TableInfo()->flds as $fld)
- {
- if($fld->name == $myId)
- {
+ foreach($this->TableInfo()->flds as $fld) {
+ if($fld->name == $myId) {
$found = true;
break;
}
$index++;
}
- if(!$found)
+ if(!$found) {
$this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
+ }
- foreach($rows as $row)
- {
+ foreach($rows as $row) {
$rowId = intval($row[$index]);
- if($rowId > 0)
- {
- if($isFirstRow)
- {
+ if($rowId > 0) {
+ if($isFirstRow) {
$isFirstRow = false;
- if(!$this->Set($row))
+ if(!$this->Set($row)) {
return false;
+ }
}
$obj = new $class($table,false,$db);
$obj->Set($row);
// TODO Copy/paste code below: bad!
- if(count($table->_hasMany) > 0)
- {
- foreach($table->_hasMany as $foreignTable)
- {
+ if(count($table->_hasMany) > 0) {
+ foreach($table->_hasMany as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
- if(!is_array($this->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
+ if(!is_array($this->$foreignName)) {
$foreignObj = $this->$foreignName;
$this->$foreignName = array(clone($foreignObj));
}
- else
- {
+ else {
$foreignObj = $obj->$foreignName;
array_push($this->$foreignName, clone($foreignObj));
}
}
}
}
- if(count($table->_belongsTo) > 0)
- {
- foreach($table->_belongsTo as $foreignTable)
- {
+ if(count($table->_belongsTo) > 0) {
+ foreach($table->_belongsTo as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
- if(!is_array($this->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
+ if(!is_array($this->$foreignName)) {
$foreignObj = $this->$foreignName;
$this->$foreignName = array(clone($foreignObj));
}
- else
- {
+ else {
$foreignObj = $obj->$foreignName;
array_push($this->$foreignName, clone($foreignObj));
}
// false on error
function Save()
{
- if ($this->_saved) $ok = $this->Update();
- else $ok = $this->Insert();
+ if ($this->_saved) {
+ $ok = $this->Update();
+ }
+ else {
+ $ok = $this->Insert();
+ }
return $ok;
}
// false on error
function Insert()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$cnt = 0;
$table = $this->TableInfo();
function Delete()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$where = $this->GenWhere($db,$table);
// returns an array of active record objects
function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
{
- $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+ $db = $this->DB();
+ if (!$db || empty($this->_table)) {
+ return false;
+ }
$table =& $this->TableInfo();
$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
// Shockingly because I want to preserve PHP4 compatibility.
function packageFind($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
{
- $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+ $db = $this->DB();
+ if (!$db || empty($this->_table)) {
+ return false;
+ }
$table =& $this->TableInfo();
$arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
{
global $ADODB_ASSOC_CASE;
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$pkey = $table->keys;
/*
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
- if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+ if (isset($fld->default_value) && strlen($fld->default_value)) {
+ continue;
+ }
else {
$this->Error("Cannot update null into $name","Replace");
return false;
}
}*/
if (is_null($val) && !empty($fld->auto_increment)) {
- continue;
- }
+ continue;
+ }
$t = $db->MetaType($fld->type);
$arr[$name] = $this->doquote($db,$val,$t);
$valarr[] = $val;
}
- if (!is_array($pkey)) $pkey = array($pkey);
+ if (!is_array($pkey)) {
+ $pkey = array($pkey);
+ }
- if ($ADODB_ASSOC_CASE == 0)
- foreach($pkey as $k => $v)
- $pkey[$k] = strtolower($v);
- elseif ($ADODB_ASSOC_CASE == 1)
- foreach($pkey as $k => $v)
- $pkey[$k] = strtoupper($v);
+ switch ($ADODB_ASSOC_CASE == 0) {
+ case ADODB_ASSOC_CASE_LOWER:
+ foreach($pkey as $k => $v) {
+ $pkey[$k] = strtolower($v);
+ }
+ break;
+ case ADODB_ASSOC_CASE_UPPER:
+ foreach($pkey as $k => $v) {
+ $pkey[$k] = strtoupper($v);
+ }
+ break;
+ }
$ok = $db->Replace($this->_table,$arr,$pkey);
if ($ok) {
// returns 0 on error, 1 on update, -1 if no change in data (no update)
function Update()
{
- $db = $this->DB(); if (!$db) return false;
+ $db = $this->DB();
+ if (!$db) {
+ return false;
+ }
$table = $this->TableInfo();
$where = $this->GenWhere($db, $table);
if (is_null($val)) {
if (isset($fld->not_null) && $fld->not_null) {
- if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+ if (isset($fld->default_value) && strlen($fld->default_value)) {
+ continue;
+ }
else {
$this->Error("Cannot set field $name to NULL","Update");
return false;
}
}
- if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
+ if (isset($this->_original[$i]) && $val === $this->_original[$i]) {
continue;
}
$valarr[] = $val;
}
- if (!$cnt) return -1;
+ if (!$cnt) {
+ return -1;
+ }
$sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
$ok = $db->Execute($sql,$valarr);
if ($ok) {
function GetAttributeNames()
{
$table = $this->TableInfo();
- if (!$table) return false;
+ if (!$table) {
+ return false;
+ }
return array_keys($table->flds);
}
{
global $_ADODB_ACTIVE_DBS;
- if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
-
+ if (empty($extra['loading'])) {
+ $extra['loading'] = ADODB_LAZY_AR;
+ }
$save = $db->SetFetchMode(ADODB_FETCH_NUM);
$table = &$tableObj->_table;
$tableInfo =& $tableObj->TableInfo();
- if(($k = reset($tableInfo->keys)))
- $myId = $k;
- else
- $myId = 'id';
+ if(($k = reset($tableInfo->keys))) {
+ $myId = $k;
+ }
+ else {
+ $myId = 'id';
+ }
$index = 0; $found = false;
/** @todo Improve by storing once and for all in table metadata */
/** @todo Also re-use info for hasManyId */
foreach($tableInfo->flds as $fld)
{
- if($fld->name == $myId)
- {
+ if($fld->name == $myId) {
$found = true;
break;
}
$index++;
}
- if(!$found)
+ if(!$found) {
$db->outp_throw("Unable to locate key $myId for $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
+ }
$qry = "select * from ".$table;
- if(ADODB_JOIN_AR == $extra['loading'])
- {
- if(!empty($relations['belongsTo']))
- {
- foreach($relations['belongsTo'] as $foreignTable)
- {
- if(($k = reset($foreignTable->TableInfo()->keys)))
- {
+ if(ADODB_JOIN_AR == $extra['loading']) {
+ if(!empty($relations['belongsTo'])) {
+ foreach($relations['belongsTo'] as $foreignTable) {
+ if(($k = reset($foreignTable->TableInfo()->keys))) {
$belongsToId = $k;
}
- else
- {
+ else {
$belongsToId = 'id';
}
$foreignTable->_table.'.'.$belongsToId;
}
}
- if(!empty($relations['hasMany']))
- {
- if(empty($relations['foreignName']))
+ if(!empty($relations['hasMany'])) {
+ if(empty($relations['foreignName'])) {
$db->outp_throw("Missing foreignName is relation specification in GetActiveRecordsClass()",'GetActiveRecordsClass');
- if(($k = reset($tableInfo->keys)))
+ }
+ if(($k = reset($tableInfo->keys))) {
$hasManyId = $k;
- else
+ }
+ else {
$hasManyId = 'id';
+ }
- foreach($relations['hasMany'] as $foreignTable)
- {
+ foreach($relations['hasMany'] as $foreignTable) {
$qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
$table.'.'.$hasManyId.'='.
$foreignTable->_table.'.'.$foreignTable->foreignKey;
}
}
}
- if (!empty($whereOrderBy))
+ if (!empty($whereOrderBy)) {
$qry .= ' WHERE '.$whereOrderBy;
- if(isset($extra['limit']))
- {
+ }
+ if(isset($extra['limit'])) {
$rows = false;
if(isset($extra['offset'])) {
$rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
// Note: to-many relationships mess around with the 'limit' parameter
$rowId = intval($row[$index]);
- if(ADODB_WORK_AR == $extra['loading'])
- {
+ if(ADODB_WORK_AR == $extra['loading']) {
$arrRef[$rowId] = $obj;
$arr[] = &$arrRef[$rowId];
- if(!isset($indices))
+ if(!isset($indices)) {
$indices = $rowId;
- else
+ }
+ else {
$indices .= ','.$rowId;
- if(!empty($relations['belongsTo']))
- {
- foreach($relations['belongsTo'] as $foreignTable)
- {
+ }
+ if(!empty($relations['belongsTo'])) {
+ foreach($relations['belongsTo'] as $foreignTable) {
$foreignTableRef = $foreignTable->foreignKey;
// First array: list of foreign ids we are looking for
- if(empty($bTos[$foreignTableRef]))
+ if(empty($bTos[$foreignTableRef])) {
$bTos[$foreignTableRef] = array();
+ }
// Second array: list of ids found
- if(empty($obj->$foreignTableRef))
+ if(empty($obj->$foreignTableRef)) {
continue;
- if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef]))
+ }
+ if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef])) {
$bTos[$foreignTableRef][$obj->$foreignTableRef] = array();
+ }
$bTos[$foreignTableRef][$obj->$foreignTableRef][] = $obj;
}
}
continue;
}
- if($rowId>0)
- {
- if(ADODB_JOIN_AR == $extra['loading'])
- {
+ if($rowId>0) {
+ if(ADODB_JOIN_AR == $extra['loading']) {
$isNewObj = !isset($uniqArr['_'.$row[0]]);
- if($isNewObj)
+ if($isNewObj) {
$uniqArr['_'.$row[0]] = $obj;
+ }
// TODO Copy/paste code below: bad!
- if(!empty($relations['hasMany']))
- {
- foreach($relations['hasMany'] as $foreignTable)
- {
+ if(!empty($relations['hasMany'])) {
+ foreach($relations['hasMany'] as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
$masterObj = &$uniqArr['_'.$row[0]];
// Assumption: this property exists in every object since they are instances of the same class
- if(!is_array($masterObj->$foreignName))
- {
+ if(!is_array($masterObj->$foreignName)) {
// Pluck!
$foreignObj = $masterObj->$foreignName;
$masterObj->$foreignName = array(clone($foreignObj));
}
- else
- {
+ else {
// Pluck pluck!
$foreignObj = $obj->$foreignName;
array_push($masterObj->$foreignName, clone($foreignObj));
}
}
}
- if(!empty($relations['belongsTo']))
- {
- foreach($relations['belongsTo'] as $foreignTable)
- {
+ if(!empty($relations['belongsTo'])) {
+ foreach($relations['belongsTo'] as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
$masterObj = &$uniqArr['_'.$row[0]];
// Assumption: this property exists in every object since they are instances of the same class
- if(!is_array($masterObj->$foreignName))
- {
+ if(!is_array($masterObj->$foreignName)) {
// Pluck!
$foreignObj = $masterObj->$foreignName;
$masterObj->$foreignName = array(clone($foreignObj));
}
- else
- {
+ else {
// Pluck pluck!
$foreignObj = $obj->$foreignName;
array_push($masterObj->$foreignName, clone($foreignObj));
}
}
}
- if(!$isNewObj)
+ if(!$isNewObj) {
unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array
+ }
}
- else if(ADODB_LAZY_AR == $extra['loading'])
- {
+ else if(ADODB_LAZY_AR == $extra['loading']) {
// Lazy loading: we need to give AdoDb a hint that we have not really loaded
// anything, all the while keeping enough information on what we wish to load.
// Let's do this by keeping the relevant info in our relationship arrays
// but get rid of the actual properties.
// We will then use PHP's __get to load these properties on-demand.
- if(!empty($relations['hasMany']))
- {
- foreach($relations['hasMany'] as $foreignTable)
- {
+ if(!empty($relations['hasMany'])) {
+ foreach($relations['hasMany'] as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
unset($obj->$foreignName);
}
}
}
- if(!empty($relations['belongsTo']))
- {
- foreach($relations['belongsTo'] as $foreignTable)
- {
+ if(!empty($relations['belongsTo'])) {
+ foreach($relations['belongsTo'] as $foreignTable) {
$foreignName = $foreignTable->foreignName;
- if(!empty($obj->$foreignName))
- {
+ if(!empty($obj->$foreignName)) {
unset($obj->$foreignName);
}
}
}
}
- if(isset($obj))
+ if(isset($obj)) {
$arr[] = $obj;
+ }
}
- if(ADODB_WORK_AR == $extra['loading'])
- {
+ if(ADODB_WORK_AR == $extra['loading']) {
// The best of both worlds?
// Here, the number of queries is constant: 1 + n*relationship.
// The second query will allow us to perform a good join
// while preserving LIMIT etc.
- if(!empty($relations['hasMany']))
- {
- foreach($relations['hasMany'] as $foreignTable)
- {
+ if(!empty($relations['hasMany'])) {
+ foreach($relations['hasMany'] as $foreignTable) {
$foreignName = $foreignTable->foreignName;
$className = ucfirst($foreignTable->_singularize($foreignName));
$obj = new $className();
$dbClassRef = $foreignTable->foreignKey;
$objs = $obj->packageFind($dbClassRef.' IN ('.$indices.')');
- foreach($objs as $obj)
- {
- if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName))
+ foreach($objs as $obj) {
+ if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName)) {
$arrRef[$obj->$dbClassRef]->$foreignName = array();
+ }
array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
}
}
}
- if(!empty($relations['belongsTo']))
- {
- foreach($relations['belongsTo'] as $foreignTable)
- {
+ if(!empty($relations['belongsTo'])) {
+ foreach($relations['belongsTo'] as $foreignTable) {
$foreignTableRef = $foreignTable->foreignKey;
- if(empty($bTos[$foreignTableRef]))
+ if(empty($bTos[$foreignTableRef])) {
continue;
- if(($k = reset($foreignTable->TableInfo()->keys)))
- {
+ }
+ if(($k = reset($foreignTable->TableInfo()->keys))) {
$belongsToId = $k;
}
- else
- {
+ else {
$belongsToId = 'id';
}
$origObjsArr = $bTos[$foreignTableRef];
/**
\mainpage
- @version V5.19 23-Apr-2014 (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ @version v5.20.1 06-Dec-2015
+ @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ @copyright (c) 2014 Damien Regad, Mark Newnham and the ADOdb community
Released under both BSD license and Lesser GPL library license. You can choose which license
you prefer.
* Set ADODB_DIR to the directory where this file resides...
* This constant was formerly called $ADODB_RootPath
*/
- if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
+ if (!defined('ADODB_DIR')) {
+ define('ADODB_DIR',dirname(__FILE__));
+ }
//==============================================================================================
// GLOBAL VARIABLES
//==============================================================================================
GLOBAL
- $ADODB_vers, // database version
+ $ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_EXTENSION, // ADODB extension installed
$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
- $ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+ $ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
// prefetching used by oracle
- if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
+ if (!defined('ADODB_PREFETCH_ROWS')) {
+ define('ADODB_PREFETCH_ROWS',10);
+ }
- /*
- Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
- This currently works only with mssql, odbc, oci8po and ibase derived drivers.
+ /**
+ * Fetch mode
+ *
+ * Set global variable $ADODB_FETCH_MODE to one of these constants or use
+ * the SetFetchMode() method to control how recordset fields are returned
+ * when fetching data.
+ *
+ * - NUM: array()
+ * - ASSOC: array('id' => 456, 'name' => 'john')
+ * - BOTH: array(0 => 456, 'id' => 456, 1 => 'john', 'name' => 'john')
+ * - DEFAULT: driver-dependent
+ */
+ define('ADODB_FETCH_DEFAULT', 0);
+ define('ADODB_FETCH_NUM', 1);
+ define('ADODB_FETCH_ASSOC', 2);
+ define('ADODB_FETCH_BOTH', 3);
- 0 = assoc lowercase field names. $rs->fields['orderid']
- 1 = assoc uppercase field names. $rs->fields['ORDERID']
- 2 = use native-case field names. $rs->fields['OrderID']
- */
+ /**
+ * Associative array case constants
+ *
+ * By defining the ADODB_ASSOC_CASE constant to one of these values, it is
+ * possible to control the case of field names (associative array's keys)
+ * when operating in ADODB_FETCH_ASSOC fetch mode.
+ * - LOWER: $rs->fields['orderid']
+ * - UPPER: $rs->fields['ORDERID']
+ * - NATIVE: $rs->fields['OrderID'] (or whatever the RDBMS will return)
+ *
+ * The default is to use native case-names.
+ *
+ * NOTE: This functionality is not implemented everywhere, it currently
+ * works only with: mssql, odbc, oci8 and ibase derived drivers
+ */
define('ADODB_ASSOC_CASE_LOWER', 0);
define('ADODB_ASSOC_CASE_UPPER', 1);
define('ADODB_ASSOC_CASE_NATIVE', 2);
- define('ADODB_FETCH_DEFAULT',0);
- define('ADODB_FETCH_NUM',1);
- define('ADODB_FETCH_ASSOC',2);
- define('ADODB_FETCH_BOTH',3);
- if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
+ if (!defined('TIMESTAMP_FIRST_YEAR')) {
+ define('TIMESTAMP_FIRST_YEAR',100);
+ }
+
+ /**
+ * AutoExecute constants
+ * (moved from adodb-pear.inc.php since they are only used in here)
+ */
+ define('DB_AUTOQUERY_INSERT', 1);
+ define('DB_AUTOQUERY_UPDATE', 2);
+
// PHP's version scheme makes converting to numbers difficult - workaround
$_adodb_ver = (float) PHP_VERSION;
define('ADODB_PHPVER',0x5200);
} else if ($_adodb_ver >= 5.0) {
define('ADODB_PHPVER',0x5000);
- } else
+ } else {
die("PHP5 or later required. You are running ".PHP_VERSION);
+ }
+ unset($_adodb_ver);
}
- //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
-
-
/**
- Accepts $src and $dest arrays, replacing string $data
+ Accepts $src and $dest arrays, replacing string $data
*/
- function ADODB_str_replace($src, $dest, $data)
- {
- if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
+ function ADODB_str_replace($src, $dest, $data) {
+ if (ADODB_PHPVER >= 0x4050) {
+ return str_replace($src,$dest,$data);
+ }
$s = reset($src);
$d = reset($dest);
return $data;
}
- function ADODB_Setup()
- {
+ function ADODB_Setup() {
GLOBAL
- $ADODB_vers, // database version
+ $ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
- $ADODB_FETCH_MODE,
+ $ADODB_FETCH_MODE,
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_FORCE_TYPE,
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES;
- if (empty($ADODB_CACHE_CLASS)) $ADODB_CACHE_CLASS = 'ADODB_Cache_File' ;
+ if (empty($ADODB_CACHE_CLASS)) {
+ $ADODB_CACHE_CLASS = 'ADODB_Cache_File' ;
+ }
$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
$ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
$ADODB_GETONE_EOF = null;
$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
} else {
// do not accept url based paths, eg. http:/ or ftp:/
- if (strpos($ADODB_CACHE_DIR,'://') !== false)
+ if (strpos($ADODB_CACHE_DIR,'://') !== false) {
die("Illegal path http:// or ftp://");
+ }
}
/**
* ADODB version as a string.
*/
- $ADODB_vers = 'V5.19 23-Apr-2014 (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
+ $ADODB_vers = 'v5.20.1 06-Dec-2015';
/**
* Determines whether recordset->RecordCount() is used.
* Set to false for highest performance -- RecordCount() will always return -1 then
* for databases that provide "virtual" recordcounts...
*/
- if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
+ if (!isset($ADODB_COUNTRECS)) {
+ $ADODB_COUNTRECS = true;
+ }
}
}
- function _adodb_safedate($s)
- {
+ function _adodb_safedate($s) {
return str_replace(array("'", '\\'), '', $s);
}
// parse date string to prevent injection attack
// date string will have one quote at beginning e.g. '3434343'
- function _adodb_safedateq($s)
- {
+ function _adodb_safedateq($s) {
$len = strlen($s);
- if ($s[0] !== "'") $s2 = "'".$s[0];
- else $s2 = "'";
+ if ($s[0] !== "'") {
+ $s2 = "'".$s[0];
+ } else {
+ $s2 = "'";
+ }
for($i=1; $i<$len; $i++) {
$ch = $s[$i];
if ($ch === '\\') {
// for transaction handling
- function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
- {
+ function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) {
//print "Errorno ($fn errno=$errno m=$errmsg) ";
$thisConnection->_transOK = false;
if ($thisConnection->_oldRaiseFn) {
var $createdir = true; // requires creation of temp dirs
- function ADODB_Cache_File()
- {
- global $ADODB_INCLUDED_CSV;
- if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+ function __construct() {
+ global $ADODB_INCLUDED_CSV;
+ if (empty($ADODB_INCLUDED_CSV)) {
+ include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+ }
}
// write serialised recordset to cache item/file
- function writecache($filename, $contents, $debug, $secs2cache)
- {
+ function writecache($filename, $contents, $debug, $secs2cache) {
return adodb_write_file($filename, $contents,$debug);
}
// load serialised recordset and unserialise it
- function &readcache($filename, &$err, $secs2cache, $rsClass)
- {
+ function &readcache($filename, &$err, $secs2cache, $rsClass) {
$rs = csv2rs($filename,$err,$secs2cache,$rsClass);
return $rs;
}
// flush all items in cache
- function flushall($debug=false)
- {
- global $ADODB_CACHE_DIR;
+ function flushall($debug=false) {
+ global $ADODB_CACHE_DIR;
- $rez = false;
+ $rez = false;
if (strlen($ADODB_CACHE_DIR) > 1) {
$rez = $this->_dirFlush($ADODB_CACHE_DIR);
- if ($debug) ADOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
- }
+ if ($debug) {
+ ADOConnection::outp( "flushall: $ADODB_CACHE_DIR<br><pre>\n". $rez."</pre>");
+ }
+ }
return $rez;
}
// flush one file in cache
- function flushcache($f, $debug=false)
- {
+ function flushcache($f, $debug=false) {
if (!@unlink($f)) {
- if ($debug) ADOConnection::outp( "flushcache: failed for $f");
+ if ($debug) {
+ ADOConnection::outp( "flushcache: failed for $f");
+ }
}
}
- function getdirname($hash)
- {
- global $ADODB_CACHE_DIR;
- if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
+ function getdirname($hash) {
+ global $ADODB_CACHE_DIR;
+ if (!isset($this->notSafeMode)) {
+ $this->notSafeMode = !ini_get('safe_mode');
+ }
return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
}
// create temp directories
- function createdir($hash, $debug)
- {
- global $ADODB_CACHE_PERMS;
+ function createdir($hash, $debug) {
+ global $ADODB_CACHE_PERMS;
$dir = $this->getdirname($hash);
if ($this->notSafeMode && !file_exists($dir)) {
$oldu = umask(0);
- if (!@mkdir($dir, empty($ADODB_CACHE_PERMS) ? 0771 : $ADODB_CACHE_PERMS)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
+ if (!@mkdir($dir, empty($ADODB_CACHE_PERMS) ? 0771 : $ADODB_CACHE_PERMS)) {
+ if(!is_dir($dir) && $debug) {
+ ADOConnection::outp("Cannot create $dir");
+ }
+ }
umask($oldu);
}
* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
* Note: $kill_top_level is used internally in the function to flush subdirectories.
*/
- function _dirFlush($dir, $kill_top_level = false)
- {
- if(!$dh = @opendir($dir)) return;
+ function _dirFlush($dir, $kill_top_level = false) {
+ if(!$dh = @opendir($dir)) return;
- while (($obj = readdir($dh))) {
- if($obj=='.' || $obj=='..') continue;
+ while (($obj = readdir($dh))) {
+ if($obj=='.' || $obj=='..') continue;
$f = $dir.'/'.$obj;
- if (strpos($obj,'.cache')) @unlink($f);
- if (is_dir($f)) $this->_dirFlush($f, true);
- }
- if ($kill_top_level === true) @rmdir($dir);
- return true;
+ if (strpos($obj,'.cache')) {
+ @unlink($f);
+ }
+ if (is_dir($f)) {
+ $this->_dirFlush($f, true);
+ }
+ }
+ if ($kill_top_level === true) {
+ @rmdir($dir);
+ }
+ return true;
}
}
var $dataProvider = 'native';
var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
var $database = ''; /// Name of database to be used.
- var $host = ''; /// The hostname of the database server
- var $user = ''; /// The username which is used to connect to the database server.
- var $password = ''; /// Password for the username. For security, we no longer store it.
- var $debug = false; /// if set to true will output sql statements
- var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
+ var $host = ''; /// The hostname of the database server
+ var $user = ''; /// The username which is used to connect to the database server.
+ var $password = ''; /// Password for the username. For security, we no longer store it.
+ var $debug = false; /// if set to true will output sql statements
+ var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
var $substr = 'substr'; /// substring operator
var $length = 'length'; /// string length ofperator
var $upperCase = 'upper'; /// uppercase function
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
- var $true = '1'; /// string that represents TRUE for a database
- var $false = '0'; /// string that represents FALSE for a database
- var $replaceQuote = "\\'"; /// string to use to replace quotes
+ var $true = '1'; /// string that represents TRUE for a database
+ var $false = '0'; /// string that represents FALSE for a database
+ var $replaceQuote = "\\'"; /// string to use to replace quotes
var $nameQuote = '"'; /// string to use to quote identifiers and names
- var $charSet=false; /// character set to use - only for interbase, postgres and oci8
+ var $charSet=false; /// character set to use - only for interbase, postgres and oci8
var $metaDatabasesSQL = '';
var $metaTablesSQL = '';
var $uniqueOrderBy = false; /// All order by columns have to be unique
var $emptyTimeStamp = ' ';
var $lastInsID = false;
//--
- var $hasInsertID = false; /// supports autoincrement ID?
- var $hasAffectedRows = false; /// supports affected rows for update/delete?
+ var $hasInsertID = false; /// supports autoincrement ID?
+ var $hasAffectedRows = false; /// supports affected rows for update/delete?
var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
- var $readOnly = false; /// this is a readonly database - used by phpLens
- var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
- var $hasGenID = false; /// can generate sequences using GenID();
- var $hasTransactions = true; /// has transactions
+ var $readOnly = false; /// this is a readonly database - used by phpLens
+ var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
+ var $hasGenID = false; /// can generate sequences using GenID();
+ var $hasTransactions = true; /// has transactions
//--
- var $genID = 0; /// sequence id used by GenID();
- var $raiseErrorFn = false; /// error function to call
- var $isoDates = false; /// accepts dates in ISO format
- var $cacheSecs = 3600; /// cache for 1 hour
+ var $genID = 0; /// sequence id used by GenID();
+ var $raiseErrorFn = false; /// error function to call
+ var $isoDates = false; /// accepts dates in ISO format
+ var $cacheSecs = 3600; /// cache for 1 hour
// memcache
var $memCache = false; /// should we use memCache instead of caching in files
var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
var $rsPrefix = "ADORecordSet_";
- var $autoCommit = true; /// do not modify this yourself - actually private
- var $transOff = 0; /// temporarily disable transactions
- var $transCnt = 0; /// count of nested transactions
+ var $autoCommit = true; /// do not modify this yourself - actually private
+ var $transOff = 0; /// temporarily disable transactions
+ var $transCnt = 0; /// count of nested transactions
var $fetchMode=false;
var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
var $bulkBind = false; // enable 2D Execute array
- //
- // PRIVATE VARS
- //
+ //
+ // PRIVATE VARS
+ //
var $_oldRaiseFn = false;
var $_transOK = null;
var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
var $_logsql = false;
var $_transmode = ''; // transaction mode
+ /*
+ * Additional parameters that may be passed to drivers in the connect string
+ * Driver must be coded to accept the parameters
+ */
+ protected $connectionParameters = array();
- static function Version()
+ /**
+ * Adds a parameter to the connection string.
+ *
+ * These parameters are added to the connection string when connecting,
+ * if the driver is coded to use it.
+ *
+ * @param string $parameter The name of the parameter to set
+ * @param string $value The value of the parameter
+ *
+ * @return null
+ *
+ * @example, for mssqlnative driver ('CharacterSet','UTF-8')
+ */
+ final public function setConnectionParameter($parameter,$value)
{
- global $ADODB_vers;
- $ok = preg_match( '/^[Vv]?([0-9]\.[0-9]+(dev|[a-z]))?/', $ADODB_vers, $matches );
- if (!$ok) return (float) substr($ADODB_vers,1);
- else return $matches[1];
+ $this->connectionParameters[$parameter] = $value;
+
+ }
+
+ static function Version() {
+ global $ADODB_vers;
+
+ // Semantic Version number matching regex
+ $regex = '^[vV]?(\d+\.\d+\.\d+' // Version number (X.Y.Z) with optional 'V'
+ . '(?:-(?:' // Optional preprod version: a '-'
+ . 'dev|' // followed by 'dev'
+ . '(?:(?:alpha|beta|rc)(?:\.\d+))' // or a preprod suffix and version number
+ . '))?)(?:\s|$)'; // Whitespace or end of string
+
+ if (!preg_match("/$regex/", $ADODB_vers, $matches)) {
+ // This should normally not happen... Return whatever is between the start
+ // of the string and the first whitespace (or the end of the string).
+ self::outp("Invalid version number: '$ADODB_vers'", 'Version');
+ $regex = '^[vV]?(.*?)(?:\s|$)';
+ preg_match("/$regex/", $ADODB_vers, $matches);
+ }
+ return $matches[1];
}
/**
@returns An array with 2 elements: $arr['string'] is the description string,
and $arr[version] is the version (also a string).
*/
- function ServerInfo()
- {
+ function ServerInfo() {
return array('description' => '', 'version' => '');
}
- function IsConnected()
- {
+ function IsConnected() {
return !empty($this->_connectionID);
}
- function _findvers($str)
- {
- if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
- else return '';
+ function _findvers($str) {
+ if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) {
+ return $arr[1];
+ } else {
+ return '';
+ }
}
/**
* All error messages go through this bottleneck function.
* You can define your own handler by defining the function name in ADODB_OUTP.
*/
- static function outp($msg,$newline=true)
- {
- global $ADODB_FLUSH,$ADODB_OUTP;
+ static function outp($msg,$newline=true) {
+ global $ADODB_FLUSH,$ADODB_OUTP;
if (defined('ADODB_OUTP')) {
$fn = ADODB_OUTP;
return;
}
- if ($newline) $msg .= "<br>\n";
+ if ($newline) {
+ $msg .= "<br>\n";
+ }
- if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
- else echo strip_tags($msg);
+ if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) {
+ echo $msg;
+ } else {
+ echo strip_tags($msg);
+ }
- if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
+ if (!empty($ADODB_FLUSH) && ob_get_length() !== false) {
+ flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
+ }
}
- function Time()
- {
+ function Time() {
$rs = $this->_Execute("select $this->sysTimeStamp");
- if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
+ if ($rs && !$rs->EOF) {
+ return $this->UnixTimeStamp(reset($rs->fields));
+ }
return false;
}
*
* @return true or false
*/
- function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
- {
- if ($argHostname != "") $this->host = $argHostname;
- if ($argUsername != "") $this->user = $argUsername;
- if ($argPassword != "") $this->password = 'not stored'; // not stored for security reasons
- if ($argDatabaseName != "") $this->database = $argDatabaseName;
+ function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) {
+ if ($argHostname != "") {
+ $this->host = $argHostname;
+ }
+ if ( strpos($this->host, ':') > 0 && isset($this->port) ) {
+ list($this->host, $this->port) = explode(":", $this->host, 2);
+ }
+ if ($argUsername != "") {
+ $this->user = $argUsername;
+ }
+ if ($argPassword != "") {
+ $this->password = 'not stored'; // not stored for security reasons
+ }
+ if ($argDatabaseName != "") {
+ $this->database = $argDatabaseName;
+ }
$this->_isPersistentConnection = false;
if ($forceNew) {
- if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) return true;
+ if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) {
+ return true;
+ }
} else {
- if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) return true;
+ if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) {
+ return true;
+ }
}
if (isset($rez)) {
$err = $this->ErrorMsg();
- if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+ if (empty($err)) {
+ $err = "Connection error to server '$argHostname' with user '$argUsername'";
+ }
$ret = false;
} else {
$err = "Missing extension for ".$this->dataProvider;
$ret = 0;
}
- if ($fn = $this->raiseErrorFn)
+ if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
-
+ }
$this->_connectionID = false;
- if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+ if ($this->debug) {
+ ADOConnection::outp( $this->host.': '.$err);
+ }
return $ret;
}
- function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
- {
+ function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) {
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
}
*
* @return true or false
*/
- function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
- {
+ function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
}
*
* @return return true or false
*/
- function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
- {
+ function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
- if (defined('ADODB_NEVER_PERSIST'))
+ if (defined('ADODB_NEVER_PERSIST')) {
return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
+ }
- if ($argHostname != "") $this->host = $argHostname;
- if ($argUsername != "") $this->user = $argUsername;
- if ($argPassword != "") $this->password = 'not stored';
- if ($argDatabaseName != "") $this->database = $argDatabaseName;
+ if ($argHostname != "") {
+ $this->host = $argHostname;
+ }
+ if ( strpos($this->host, ':') > 0 && isset($this->port) ) {
+ list($this->host, $this->port) = explode(":", $this->host, 2);
+ }
+ if ($argUsername != "") {
+ $this->user = $argUsername;
+ }
+ if ($argPassword != "") {
+ $this->password = 'not stored';
+ }
+ if ($argDatabaseName != "") {
+ $this->database = $argDatabaseName;
+ }
$this->_isPersistentConnection = true;
- if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) return true;
+ if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) {
+ return true;
+ }
if (isset($rez)) {
$err = $this->ErrorMsg();
- if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+ if (empty($err)) {
+ $err = "Connection error to server '$argHostname' with user '$argUsername'";
+ }
$ret = false;
} else {
$err = "Missing extension for ".$this->dataProvider;
}
$this->_connectionID = false;
- if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+ if ($this->debug) {
+ ADOConnection::outp( $this->host.': '.$err);
+ }
return $ret;
}
- function outp_throw($msg,$src='WARN',$sql='')
- {
+ function outp_throw($msg,$src='WARN',$sql='') {
if (defined('ADODB_ERROR_HANDLER') && ADODB_ERROR_HANDLER == 'adodb_throw') {
adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
return;
}
// create cache class. Code is backward compat with old memcache implementation
- function _CreateCache()
- {
- global $ADODB_CACHE, $ADODB_CACHE_CLASS;
+ function _CreateCache() {
+ global $ADODB_CACHE, $ADODB_CACHE_CLASS;
if ($this->memCache) {
- global $ADODB_INCLUDED_MEMCACHE;
-
- if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
- $ADODB_CACHE = new ADODB_Cache_MemCache($this);
- } else
- $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
+ global $ADODB_INCLUDED_MEMCACHE;
+ if (empty($ADODB_INCLUDED_MEMCACHE)) {
+ include_once(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+ }
+ $ADODB_CACHE = new ADODB_Cache_MemCache($this);
+ } else {
+ $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
+ }
}
// Format date column in sql string given an input format that understands Y M D
- function SQLDate($fmt, $col=false)
- {
- if (!$col) $col = $this->sysDate;
+ function SQLDate($fmt, $col=false) {
+ if (!$col) {
+ $col = $this->sysDate;
+ }
return $col; // child class implement
}
* @param sql SQL to send to database
*
* @return return FALSE, or the prepared statement, or the original sql if
- * if the database does not support prepare.
+ * if the database does not support prepare.
*
*/
- function Prepare($sql)
- {
+ function Prepare($sql) {
return $sql;
}
* @param sql SQL to send to database
*
* @return return FALSE, or the prepared statement, or the original sql if
- * if the database does not support prepare.
+ * if the database does not support prepare.
*
*/
- function PrepareSP($sql,$param=true)
- {
+ function PrepareSP($sql,$param=true) {
return $this->Prepare($sql,$param);
}
/**
* PEAR DB Compat
*/
- function Quote($s)
- {
+ function Quote($s) {
return $this->qstr($s,false);
}
/**
- Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
- */
- function QMagic($s)
- {
+ * Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
+ */
+ function QMagic($s) {
return $this->qstr($s,get_magic_quotes_gpc());
}
- function q(&$s)
- {
- #if (!empty($this->qNull)) if ($s == 'null') return $s;
+ function q(&$s) {
+ //if (!empty($this->qNull && $s == 'null') {
+ // return $s;
+ //}
$s = $this->qstr($s,false);
}
/**
* PEAR DB Compat - do not use internally.
*/
- function ErrorNative()
- {
+ function ErrorNative() {
return $this->ErrorNo();
}
/**
* PEAR DB Compat - do not use internally.
*/
- function nextId($seq_name)
- {
+ function nextId($seq_name) {
return $this->GenID($seq_name);
}
/**
- * Lock a row, will escalate and lock the table if row locking not supported
- * will normally free the lock at the end of the transaction
+ * Lock a row, will escalate and lock the table if row locking not supported
+ * will normally free the lock at the end of the transaction
*
- * @param $table name of table to lock
- * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
+ * @param $table name of table to lock
+ * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
*/
- function RowLock($table,$where,$col='1 as adodbignore')
- {
+ function RowLock($table,$where,$col='1 as adodbignore') {
return false;
}
- function CommitLock($table)
- {
+ function CommitLock($table) {
return $this->CommitTrans();
}
- function RollbackLock($table)
- {
+ function RollbackLock($table) {
return $this->RollbackTrans();
}
* PEAR DB Compat - do not use internally.
*
* The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
- * for easy porting :-)
+ * for easy porting :-)
*
* @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
* @returns The previous fetch mode
*/
- function SetFetchMode($mode)
- {
+ function SetFetchMode($mode) {
$old = $this->fetchMode;
$this->fetchMode = $mode;
if ($old === false) {
- global $ADODB_FETCH_MODE;
+ global $ADODB_FETCH_MODE;
return $ADODB_FETCH_MODE;
}
return $old;
/**
* PEAR DB Compat - do not use internally.
*/
- function Query($sql, $inputarr=false)
- {
+ function Query($sql, $inputarr=false) {
$rs = $this->Execute($sql, $inputarr);
- if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+ if (!$rs && defined('ADODB_PEAR')) {
+ return ADODB_PEAR_Error();
+ }
return $rs;
}
/**
* PEAR DB Compat - do not use internally
*/
- function LimitQuery($sql, $offset, $count, $params=false)
- {
+ function LimitQuery($sql, $offset, $count, $params=false) {
$rs = $this->SelectLimit($sql, $count, $offset, $params);
- if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+ if (!$rs && defined('ADODB_PEAR')) {
+ return ADODB_PEAR_Error();
+ }
return $rs;
}
/**
* PEAR DB Compat - do not use internally
*/
- function Disconnect()
- {
+ function Disconnect() {
return $this->Close();
}
* @param string $type (unused)
* @return string query parameter placeholder
*/
- function Param($name,$type='C')
- {
+ function Param($name,$type='C') {
return '?';
}
/*
InParameter and OutParameter are self-documenting versions of Parameter().
*/
- function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
- {
+ function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) {
return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
}
/*
*/
- function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
- {
+ function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) {
return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
}
@param [$type] The data type of $var. Legal values depend on driver.
*/
- function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
- {
+ function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) {
return false;
}
- function IgnoreErrors($saveErrs=false)
- {
+ function IgnoreErrors($saveErrs=false) {
if (!$saveErrs) {
$saveErrs = array($this->raiseErrorFn,$this->_transOK);
$this->raiseErrorFn = false;
}
/**
- Improved method of initiating a transaction. Used together with CompleteTrans().
- Advantages include:
-
- a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
- Only the outermost block is treated as a transaction.<br>
- b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
- c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
- are disabled, making it backward compatible.
- */
- function StartTrans($errfn = 'ADODB_TransMonitor')
- {
+ * Improved method of initiating a transaction. Used together with CompleteTrans().
+ * Advantages include:
+ *
+ * a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
+ * Only the outermost block is treated as a transaction.<br>
+ * b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
+ * c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
+ * are disabled, making it backward compatible.
+ */
+ function StartTrans($errfn = 'ADODB_TransMonitor') {
if ($this->transOff > 0) {
$this->transOff += 1;
return true;
$this->raiseErrorFn = $errfn;
$this->_transOK = true;
- if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+ if ($this->debug && $this->transCnt > 0) {
+ ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+ }
$ok = $this->BeginTrans();
$this->transOff = 1;
return $ok;
and if set to false force rollback even if no SQL error detected.
@returns true on commit, false on rollback.
*/
- function CompleteTrans($autoComplete = true)
- {
+ function CompleteTrans($autoComplete = true) {
if ($this->transOff > 1) {
$this->transOff -= 1;
return true;
if ($this->_transOK && $autoComplete) {
if (!$this->CommitTrans()) {
$this->_transOK = false;
- if ($this->debug) ADOConnection::outp("Smart Commit failed");
- } else
- if ($this->debug) ADOConnection::outp("Smart Commit occurred");
+ if ($this->debug) {
+ ADOConnection::outp("Smart Commit failed");
+ }
+ } else {
+ if ($this->debug) {
+ ADOConnection::outp("Smart Commit occurred");
+ }
+ }
} else {
$this->_transOK = false;
$this->RollbackTrans();
- if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
+ if ($this->debug) {
+ ADOCOnnection::outp("Smart Rollback occurred");
+ }
}
return $this->_transOK;
/*
At the end of a StartTrans/CompleteTrans block, perform a rollback.
*/
- function FailTrans()
- {
+ function FailTrans() {
if ($this->debug)
if ($this->transOff == 0) {
ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
/**
Check if transaction has failed, only for Smart Transactions.
*/
- function HasFailedTrans()
- {
- if ($this->transOff > 0) return $this->_transOK == false;
+ function HasFailedTrans() {
+ if ($this->transOff > 0) {
+ return $this->_transOK == false;
+ }
return false;
}
*
* @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
* @param [inputarr] holds the input data to bind to. Null elements will be set to null.
- * @return RecordSet or false
+ * @return RecordSet or false
*/
- function Execute($sql,$inputarr=false)
- {
+ function Execute($sql,$inputarr=false) {
if ($this->fnExecute) {
$fn = $this->fnExecute;
$ret = $fn($this,$sql,$inputarr);
- if (isset($ret)) return $ret;
+ if (isset($ret)) {
+ return $ret;
+ }
}
if ($inputarr !== false) {
- if (!is_array($inputarr)) $inputarr = array($inputarr);
+ if (!is_array($inputarr)) {
+ $inputarr = array($inputarr);
+ }
$element0 = reset($inputarr);
# is_object check because oci8 descriptors can be passed in
unset($element0);
if (!is_array($sql) && !$this->_bindInputArray) {
+ // @TODO this would consider a '?' within a string as a parameter...
$sqlarr = explode('?',$sql);
$nparams = sizeof($sqlarr)-1;
- if (!$array_2d) $inputarr = array($inputarr);
+
+ // Make sure the number of parameters provided in the input
+ // array matches what the query expects
+ if ($nparams != count($inputarr)) {
+ $this->outp_throw(
+ "Input array has " . count($inputarr) .
+ " params, does not match query: '" . htmlspecialchars($sql) . "'",
+ 'Execute'
+ );
+ return false;
+ }
+
+ if (!$array_2d) {
+ $inputarr = array($inputarr);
+ }
foreach($inputarr as $arr) {
$sql = ''; $i = 0;
// from Ron Baldwin <ron.baldwin#sourceprose.com>
// Only quote string types
$typ = gettype($v);
- if ($typ == 'string')
+ if ($typ == 'string') {
//New memory copy of input created here -mikefedyk
$sql .= $this->qstr($v);
- else if ($typ == 'double')
+ } else if ($typ == 'double') {
$sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
- else if ($typ == 'boolean')
+ } else if ($typ == 'boolean') {
$sql .= $v ? $this->true : $this->false;
- else if ($typ == 'object') {
- if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
- else $sql .= $this->qstr((string) $v);
- } else if ($v === null)
+ } else if ($typ == 'object') {
+ if (method_exists($v, '__toString')) {
+ $sql .= $this->qstr($v->__toString());
+ } else {
+ $sql .= $this->qstr((string) $v);
+ }
+ } else if ($v === null) {
$sql .= 'NULL';
- else
+ } else {
$sql .= $v;
+ }
$i += 1;
- if ($i == $nparams) break;
+ if ($i == $nparams) {
+ break;
+ }
} // while
if (isset($sqlarr[$i])) {
$sql .= $sqlarr[$i];
- if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
- } else if ($i != sizeof($sqlarr))
+ if ($i+1 != sizeof($sqlarr)) {
+ $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
+ }
+ } else if ($i != sizeof($sqlarr)) {
$this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute');
+ }
$ret = $this->_Execute($sql);
- if (!$ret) return $ret;
+ if (!$ret) {
+ return $ret;
+ }
}
} else {
if ($array_2d) {
- if (is_string($sql))
+ if (is_string($sql)) {
$stmt = $this->Prepare($sql);
- else
+ } else {
$stmt = $sql;
+ }
foreach($inputarr as $arr) {
$ret = $this->_Execute($stmt,$arr);
- if (!$ret) return $ret;
+ if (!$ret) {
+ return $ret;
+ }
}
} else {
$ret = $this->_Execute($sql,$inputarr);
return $ret;
}
+ function _Execute($sql,$inputarr=false) {
+ // ExecuteCursor() may send non-string queries (such as arrays),
+ // so we need to ignore those.
+ if( is_string($sql) ) {
+ // Strips keyword used to help generate SELECT COUNT(*) queries
+ // from SQL if it exists.
+ $sql = ADODB_str_replace( '_ADODB_COUNT', '', $sql );
+ }
- function _Execute($sql,$inputarr=false)
- {
if ($this->debug) {
global $ADODB_INCLUDED_LIB;
- if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+ if (empty($ADODB_INCLUDED_LIB)) {
+ include(ADODB_DIR.'/adodb-lib.inc.php');
+ }
$this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
} else {
$this->_queryID = @$this->_query($sql,$inputarr);
// OK, query executed
// ************************
- if ($this->_queryID === false) { // error handling if query fails
- if ($this->debug == 99) adodb_backtrace(true,5);
+ // error handling if query fails
+ if ($this->_queryID === false) {
+ if ($this->debug == 99) {
+ adodb_backtrace(true,5);
+ }
$fn = $this->raiseErrorFn;
if ($fn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
}
- $false = false;
- return $false;
+ return false;
}
- if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
+ // return simplified recordset for inserts/updates/deletes with lower overhead
+ if ($this->_queryID === true) {
$rsclass = $this->rsPrefix.'empty';
$rs = (class_exists($rsclass)) ? new $rsclass(): new ADORecordSet_empty();
$rs = new $rsclass($this->_queryID,$this->fetchMode);
$rs->connection = $this; // Pablo suggestion
$rs->Init();
- if (is_array($sql)) $rs->sql = $sql[0];
- else $rs->sql = $sql;
+ if (is_array($sql)) {
+ $rs->sql = $sql[0];
+ } else {
+ $rs->sql = $sql;
+ }
if ($rs->_numOfRows <= 0) {
- global $ADODB_COUNTRECS;
+ global $ADODB_COUNTRECS;
if ($ADODB_COUNTRECS) {
if (!$rs->EOF) {
$rs = $this->_rs2rs($rs,-1,-1,!is_array($sql));
return $rs;
}
- function CreateSequence($seqname='adodbseq',$startID=1)
- {
- if (empty($this->_genSeqSQL)) return false;
+ function CreateSequence($seqname='adodbseq',$startID=1) {
+ if (empty($this->_genSeqSQL)) {
+ return false;
+ }
return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
}
- function DropSequence($seqname='adodbseq')
- {
- if (empty($this->_dropSeqSQL)) return false;
+ function DropSequence($seqname='adodbseq') {
+ if (empty($this->_dropSeqSQL)) {
+ return false;
+ }
return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
}
* @param startID if sequence does not exist, start at this ID
* @return 0 if not supported, otherwise a sequence id
*/
- function GenID($seqname='adodbseq',$startID=1)
- {
+ function GenID($seqname='adodbseq',$startID=1) {
if (!$this->hasGenID) {
return 0; // formerly returns false pre 1.60
}
$createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
$rs = $this->Execute($getnext);
}
- if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
- else $this->genID = 0; // false
+ if ($rs && !$rs->EOF) {
+ $this->genID = reset($rs->fields);
+ } else {
+ $this->genID = 0; // false
+ }
- if ($rs) $rs->Close();
+ if ($rs) {
+ $rs->Close();
+ }
return $this->genID;
}
* @param $column string name of the column, not needed by all databases (eg. mysql), default ''
* @return the last inserted ID. Not all databases support this.
*/
- function Insert_ID($table='',$column='')
- {
- if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
- if ($this->hasInsertID) return $this->_insertid($table,$column);
+ function Insert_ID($table='',$column='') {
+ if ($this->_logsql && $this->lastInsID) {
+ return $this->lastInsID;
+ }
+ if ($this->hasInsertID) {
+ return $this->_insertid($table,$column);
+ }
if ($this->debug) {
ADOConnection::outp( '<p>Insert_ID error</p>');
adodb_backtrace();
* @return the last inserted ID. All databases support this. But aware possible
* problems in multiuser environments. Heavy test this before deploying.
*/
- function PO_Insert_ID($table="", $id="")
- {
- if ($this->hasInsertID){
- return $this->Insert_ID($table,$id);
- } else {
- return $this->GetOne("SELECT MAX($id) FROM $table");
- }
+ function PO_Insert_ID($table="", $id="") {
+ if ($this->hasInsertID){
+ return $this->Insert_ID($table,$id);
+ } else {
+ return $this->GetOne("SELECT MAX($id) FROM $table");
+ }
}
/**
* @return # rows affected by UPDATE/DELETE
*/
- function Affected_Rows()
- {
+ function Affected_Rows() {
if ($this->hasAffectedRows) {
if ($this->fnExecute === 'adodb_log_sql') {
- if ($this->_logsql && $this->_affected !== false) return $this->_affected;
+ if ($this->_logsql && $this->_affected !== false) {
+ return $this->_affected;
+ }
}
$val = $this->_affectedrows();
return ($val < 0) ? false : $val;
}
- if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+ if ($this->debug) {
+ ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+ }
return false;
}
/**
* @return the last error message
*/
- function ErrorMsg()
- {
- if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
- else return '';
+ function ErrorMsg() {
+ if ($this->_errorMsg) {
+ return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
+ } else {
+ return '';
+ }
}
/**
* @return the last error number. Normally 0 means no error.
*/
- function ErrorNo()
- {
+ function ErrorNo() {
return ($this->_errorMsg) ? -1 : 0;
}
- function MetaError($err=false)
- {
+ function MetaError($err=false) {
include_once(ADODB_DIR."/adodb-error.inc.php");
- if ($err === false) $err = $this->ErrorNo();
+ if ($err === false) {
+ $err = $this->ErrorNo();
+ }
return adodb_error($this->dataProvider,$this->databaseType,$err);
}
- function MetaErrorMsg($errno)
- {
+ function MetaErrorMsg($errno) {
include_once(ADODB_DIR."/adodb-error.inc.php");
return adodb_errormsg($errno);
}
/**
* @returns an array with the primary key columns in it.
*/
- function MetaPrimaryKeys($table, $owner=false)
- {
+ function MetaPrimaryKeys($table, $owner=false) {
// owner not used in base class - see oci8
$p = array();
$objs = $this->MetaColumns($table);
if ($objs) {
foreach($objs as $v) {
- if (!empty($v->primary_key))
+ if (!empty($v->primary_key)) {
$p[] = $v->name;
+ }
}
}
- if (sizeof($p)) return $p;
- if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
+ if (sizeof($p)) {
+ return $p;
+ }
+ if (function_exists('ADODB_VIEW_PRIMARYKEYS')) {
return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
+ }
return false;
}
/**
* @returns assoc array where keys are tables, and values are foreign keys
*/
- function MetaForeignKeys($table, $owner=false, $upper=false)
- {
+ function MetaForeignKeys($table, $owner=false, $upper=false) {
return false;
}
/**
* Choose a database to connect to. Many databases do not support this.
*
- * @param dbName is the name of the database to select
- * @return true or false
+ * @param dbName is the name of the database to select
+ * @return true or false
*/
- function SelectDB($dbName)
- {return false;}
+ function SelectDB($dbName) {return false;}
/**
* @param [secs2cache] is a private parameter only used by jlim
* @return the recordset ($rs->databaseType == 'array')
*/
- function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
- {
+ function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) {
if ($this->hasTop && $nrows > 0) {
- // suggested by Reinhard Balling. Access requires top after distinct
- // Informix requires first before distinct - F Riosa
+ // suggested by Reinhard Balling. Access requires top after distinct
+ // Informix requires first before distinct - F Riosa
$ismssql = (strpos($this->databaseType,'mssql') !== false);
- if ($ismssql) $isaccess = false;
- else $isaccess = (strpos($this->databaseType,'access') !== false);
-
- if ($offset <= 0) {
+ if ($ismssql) {
+ $isaccess = false;
+ } else {
+ $isaccess = (strpos($this->databaseType,'access') !== false);
+ }
+ if ($offset <= 0) {
// access includes ties in result
if ($isaccess) {
$sql = preg_replace(
$ADODB_COUNTRECS = false;
- if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
- else $rs = $this->Execute($sql,$inputarr);
+ if ($secs2cache != 0) {
+ $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
+ } else {
+ $rs = $this->Execute($sql,$inputarr);
+ }
$ADODB_COUNTRECS = $savec;
if ($rs && !$rs->EOF) {
*
* @param rs the recordset to serialize
*/
- function SerializableRS(&$rs)
- {
+ function SerializableRS(&$rs) {
$rs2 = $this->_rs2rs($rs);
$ignore = false;
$rs2->connection = $ignore;
* old $rs will be closed.
*
* @param rs the recordset to copy
- * @param [nrows] number of rows to retrieve (optional)
- * @param [offset] offset by number of rows (optional)
- * @return the new recordset
+ * @param [nrows] number of rows to retrieve (optional)
+ * @param [offset] offset by number of rows (optional)
+ * @return the new recordset
*/
- function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
- {
+ function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) {
if (! $rs) {
- $false = false;
- return $false;
+ return false;
}
$dbtype = $rs->databaseType;
if (!$dbtype) {
$arr = $rs->GetArrayLimit($nrows,$offset);
//print_r($arr);
- if ($close) $rs->Close();
+ if ($close) {
+ $rs->Close();
+ }
$arrayClass = $this->arrayClass;
/*
* Return all rows. Compat with PEAR DB
*/
- function GetAll($sql, $inputarr=false)
- {
+ function GetAll($sql, $inputarr=false) {
$arr = $this->GetArray($sql,$inputarr);
return $arr;
}
- function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
- {
+ function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) {
$rs = $this->Execute($sql, $inputarr);
if (!$rs) {
- $false = false;
- return $false;
+ return false;
}
$arr = $rs->GetAssoc($force_array,$first2cols);
return $arr;
}
- function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
- {
+ function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) {
if (!is_numeric($secs2cache)) {
$first2cols = $force_array;
$force_array = $inputarr;
}
$rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
if (!$rs) {
- $false = false;
- return $false;
+ return false;
}
$arr = $rs->GetAssoc($force_array,$first2cols);
return $arr;
* @param sql SQL statement
* @param [inputarr] input bind array
*/
- function GetOne($sql,$inputarr=false)
- {
- global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
+ function GetOne($sql,$inputarr=false) {
+ global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
+
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$ret = false;
$rs = $this->Execute($sql,$inputarr);
if ($rs) {
- if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
- else $ret = reset($rs->fields);
+ if ($rs->EOF) {
+ $ret = $ADODB_GETONE_EOF;
+ } else {
+ $ret = reset($rs->fields);
+ }
$rs->Close();
}
}
// $where should include 'WHERE fld=value'
- function GetMedian($table, $field,$where = '')
- {
+ function GetMedian($table, $field,$where = '') {
$total = $this->GetOne("select count(*) from $table $where");
- if (!$total) return false;
+ if (!$total) {
+ return false;
+ }
$midrow = (integer) ($total/2);
$rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
- if ($rs && !$rs->EOF) return reset($rs->fields);
+ if ($rs && !$rs->EOF) {
+ return reset($rs->fields);
+ }
return false;
}
- function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
- {
- global $ADODB_GETONE_EOF;
+ function CacheGetOne($secs2cache,$sql=false,$inputarr=false) {
+ global $ADODB_GETONE_EOF;
+
$ret = false;
$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
if ($rs) {
- if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
- else $ret = reset($rs->fields);
+ if ($rs->EOF) {
+ $ret = $ADODB_GETONE_EOF;
+ } else {
+ $ret = reset($rs->fields);
+ }
$rs->Close();
}
return $ret;
}
- function GetCol($sql, $inputarr = false, $trim = false)
- {
+ function GetCol($sql, $inputarr = false, $trim = false) {
- $rs = $this->Execute($sql, $inputarr);
- if ($rs) {
+ $rs = $this->Execute($sql, $inputarr);
+ if ($rs) {
$rv = array();
- if ($trim) {
+ if ($trim) {
while (!$rs->EOF) {
$rv[] = trim(reset($rs->fields));
$rs->MoveNext();
- }
+ }
} else {
while (!$rs->EOF) {
$rv[] = reset($rs->fields);
$rs->MoveNext();
- }
+ }
}
- $rs->Close();
- } else
+ $rs->Close();
+ } else {
$rv = false;
- return $rv;
+ }
+ return $rv;
}
- function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
- {
- $rs = $this->CacheExecute($secs, $sql, $inputarr);
- if ($rs) {
+ function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) {
+ $rs = $this->CacheExecute($secs, $sql, $inputarr);
+ if ($rs) {
$rv = array();
if ($trim) {
while (!$rs->EOF) {
$rv[] = trim(reset($rs->fields));
$rs->MoveNext();
- }
+ }
} else {
while (!$rs->EOF) {
$rv[] = reset($rs->fields);
$rs->MoveNext();
- }
+ }
}
- $rs->Close();
- } else
+ $rs->Close();
+ } else
$rv = false;
- return $rv;
+ return $rv;
}
- function Transpose(&$rs,$addfieldnames=true)
- {
+ function Transpose(&$rs,$addfieldnames=true) {
$rs2 = $this->_rs2rs($rs);
- $false = false;
- if (!$rs2) return $false;
+ if (!$rs2) {
+ return false;
+ }
$rs2->_transpose($addfieldnames);
return $rs2;
If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
*/
- function OffsetDate($dayFraction,$date=false)
- {
- if (!$date) $date = $this->sysDate;
+ function OffsetDate($dayFraction,$date=false) {
+ if (!$date) {
+ $date = $this->sysDate;
+ }
return '('.$date.'+'.$dayFraction.')';
}
* @param sql SQL statement
* @param [inputarr] input bind array
*/
- function GetArray($sql,$inputarr=false)
- {
- global $ADODB_COUNTRECS;
+ function GetArray($sql,$inputarr=false) {
+ global $ADODB_COUNTRECS;
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$cls = ADODB_PEAR_Error();
return $cls;
} else {
- $false = false;
- return $false;
+ return false;
}
$arr = $rs->GetArray();
$rs->Close();
return $arr;
}
- function CacheGetAll($secs2cache,$sql=false,$inputarr=false)
- {
+ function CacheGetAll($secs2cache,$sql=false,$inputarr=false) {
$arr = $this->CacheGetArray($secs2cache,$sql,$inputarr);
return $arr;
}
- function CacheGetArray($secs2cache,$sql=false,$inputarr=false)
- {
- global $ADODB_COUNTRECS;
+ function CacheGetArray($secs2cache,$sql=false,$inputarr=false) {
+ global $ADODB_COUNTRECS;
$savec = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$cls = ADODB_PEAR_Error();
return $cls;
} else {
- $false = false;
- return $false;
+ return false;
}
$arr = $rs->GetArray();
$rs->Close();
return $arr;
}
- function GetRandRow($sql, $arr= false)
- {
+ function GetRandRow($sql, $arr= false) {
$rezarr = $this->GetAll($sql, $arr);
$sz = sizeof($rezarr);
return $rezarr[abs(rand()) % $sz];
* @param sql SQL statement
* @param [inputarr] input bind array
*/
- function GetRow($sql,$inputarr=false)
- {
- global $ADODB_COUNTRECS;
+ function GetRow($sql,$inputarr=false) {
+ global $ADODB_COUNTRECS;
+
$crecs = $ADODB_COUNTRECS;
$ADODB_COUNTRECS = false;
$ADODB_COUNTRECS = $crecs;
if ($rs) {
- if (!$rs->EOF) $arr = $rs->fields;
- else $arr = array();
+ if (!$rs->EOF) {
+ $arr = $rs->fields;
+ } else {
+ $arr = array();
+ }
$rs->Close();
return $arr;
}
- $false = false;
- return $false;
+ return false;
}
- function CacheGetRow($secs2cache,$sql=false,$inputarr=false)
- {
+ function CacheGetRow($secs2cache,$sql=false,$inputarr=false) {
$rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
if ($rs) {
- if (!$rs->EOF) $arr = $rs->fields;
- else $arr = array();
+ if (!$rs->EOF) {
+ $arr = $rs->fields;
+ } else {
+ $arr = array();
+ }
$rs->Close();
return $arr;
}
- $false = false;
- return $false;
+ return false;
}
/**
* returns 0 = fail, 1 = update, 2 = insert
*/
- function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
- {
+ function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) {
global $ADODB_INCLUDED_LIB;
- if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+ if (empty($ADODB_INCLUDED_LIB)) {
+ include(ADODB_DIR.'/adodb-lib.inc.php');
+ }
return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
}
* @param [inputarr] array of bind variables
* @return the recordset ($rs->databaseType == 'array')
*/
- function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
- {
+ function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false) {
if (!is_numeric($secs2cache)) {
- if ($sql === false) $sql = -1;
- if ($offset == -1) $offset = false;
- // sql, nrows, offset,inputarr
+ if ($sql === false) {
+ $sql = -1;
+ }
+ if ($offset == -1) {
+ $offset = false;
+ }
+ // sql, nrows, offset,inputarr
$rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
} else {
- if ($sql === false) $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
+ if ($sql === false) {
+ $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
+ }
$rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
}
return $rs;
}
-
/**
* Flush cached recordsets that match a particular $sql statement.
* If $sql == false, then we purge all files in the cache.
*/
+ function CacheFlush($sql=false,$inputarr=false) {
+ global $ADODB_CACHE_DIR, $ADODB_CACHE;
- /**
- * Flush cached recordsets that match a particular $sql statement.
- * If $sql == false, then we purge all files in the cache.
- */
- function CacheFlush($sql=false,$inputarr=false)
- {
- global $ADODB_CACHE_DIR, $ADODB_CACHE;
-
- if (empty($ADODB_CACHE)) return false;
+ # Create cache if it does not exist
+ if (empty($ADODB_CACHE)) {
+ $this->_CreateCache();
+ }
if (!$sql) {
- $ADODB_CACHE->flushall($this->debug);
- return;
- }
+ $ADODB_CACHE->flushall($this->debug);
+ return;
+ }
$f = $this->_gencachename($sql.serialize($inputarr),false);
return $ADODB_CACHE->flushcache($f, $this->debug);
* Assuming that we can have 50,000 files per directory with good performance,
* then we can scale to 12.8 million unique cached recordsets. Wow!
*/
- function _gencachename($sql,$createdir)
- {
- global $ADODB_CACHE, $ADODB_CACHE_DIR;
+ function _gencachename($sql,$createdir) {
+ global $ADODB_CACHE, $ADODB_CACHE_DIR;
if ($this->fetchMode === false) {
- global $ADODB_FETCH_MODE;
+ global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
} else {
$mode = $this->fetchMode;
}
$m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
- if (!$ADODB_CACHE->createdir) return $m;
- if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
- else $dir = $ADODB_CACHE->createdir($m, $this->debug);
+ if (!$ADODB_CACHE->createdir) {
+ return $m;
+ }
+ if (!$createdir) {
+ $dir = $ADODB_CACHE->getdirname($m);
+ } else {
+ $dir = $ADODB_CACHE->createdir($m, $this->debug);
+ }
return $dir.'/adodb_'.$m.'.cache';
}
* This is an optional parameter.
* @param sql SQL statement to execute
* @param [inputarr] holds the input data to bind to
- * @return RecordSet or false
+ * @return RecordSet or false
*/
- function CacheExecute($secs2cache,$sql=false,$inputarr=false)
- {
- global $ADODB_CACHE;
+ function CacheExecute($secs2cache,$sql=false,$inputarr=false) {
+ global $ADODB_CACHE;
- if (empty($ADODB_CACHE)) $this->_CreateCache();
+ if (empty($ADODB_CACHE)) {
+ $this->_CreateCache();
+ }
if (!is_numeric($secs2cache)) {
$inputarr = $sql;
if (get_magic_quotes_runtime() && !$this->memCache) {
ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
}
- if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
+ if ($this->debug !== -1) {
+ ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
+ }
}
$rs = $this->Execute($sqlparam,$inputarr);
if ($rs) {
-
$eof = $rs->EOF;
$rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
$rs->timeCreated = time(); // used by caching
// do not call error handling for just a warning
}
- if ($this->debug) ADOConnection::outp( " ".$em);
+ if ($this->debug) {
+ ADOConnection::outp( " ".$em);
+ }
}
if ($rs->EOF && !$eof) {
$rs->MoveFirst();
$rs->connection = $this; // Pablo suggestion
}
- } else if (!$this->memCache)
+ } else if (!$this->memCache) {
$ADODB_CACHE->flushcache($md5file);
+ }
} else {
$this->_errorMsg = '';
$this->_errorCode = 0;
$fn = $this->fnCacheExecute;
$fn($this, $secs2cache, $sql, $inputarr);
}
- // ok, set cached object found
+ // ok, set cached object found
$rs->connection = $this; // Pablo suggestion
if ($this->debug){
- if ($this->debug == 99) adodb_backtrace();
+ if ($this->debug == 99) {
+ adodb_backtrace();
+ }
$inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
$ttl = $rs->timeCreated + $secs2cache - time();
$s = is_array($sql) ? $sql[0] : $sql;
- if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
+ if ($inBrowser) {
+ $s = '<i>'.htmlspecialchars($s).'</i>';
+ }
ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
}
$forceUpdate means that even if the data has not changed, perform update.
*/
- function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
- {
- $false = false;
- $sql = 'SELECT * FROM '.$table;
- if ($where!==FALSE) $sql .= ' WHERE '.$where;
- else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
- $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
- return $false;
+ function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = false, $forceUpdate = true, $magicq = false) {
+ if ($where === false && ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) ) {
+ $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause', 'AutoExecute');
+ return false;
+ }
+
+ $sql = "SELECT * FROM $table";
+ $rs = $this->SelectLimit($sql, 1);
+ if (!$rs) {
+ return false; // table does not exist
}
- $rs = $this->SelectLimit($sql,1);
- if (!$rs) return $false; // table does not exist
$rs->tableName = $table;
+ if ($where !== false) {
+ $sql .= " WHERE $where";
+ }
$rs->sql = $sql;
- switch((string) $mode) {
- case 'UPDATE':
- case '2':
- $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
- break;
- case 'INSERT':
- case '1':
- $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
- break;
- default:
- $this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
- return $false;
+ switch($mode) {
+ case 'UPDATE':
+ case DB_AUTOQUERY_UPDATE:
+ $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
+ break;
+ case 'INSERT':
+ case DB_AUTOQUERY_INSERT:
+ $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
+ break;
+ default:
+ $this->outp_throw("AutoExecute: Unknown mode=$mode", 'AutoExecute');
+ return false;
}
- $ret = false;
- if ($sql) $ret = $this->Execute($sql);
- if ($ret) $ret = true;
- return $ret;
+ return $sql && $this->Execute($sql);
}
*
* "Jonathan Younger" <jyounger@unilab.com>
*/
- function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
- {
+ function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null) {
global $ADODB_INCLUDED_LIB;
// ********************************************************
// This is here to maintain compatibility
// with older adodb versions. Sets force type to force nulls if $forcenulls is set.
if (!isset($force)) {
- global $ADODB_FORCE_TYPE;
- $force = $ADODB_FORCE_TYPE;
+ global $ADODB_FORCE_TYPE;
+ $force = $ADODB_FORCE_TYPE;
}
// ********************************************************
- if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+ if (empty($ADODB_INCLUDED_LIB)) {
+ include(ADODB_DIR.'/adodb-lib.inc.php');
+ }
return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
}
* Note: This function should only be used on a recordset
* that is run against a single table.
*/
- function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
- {
+ function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null) {
global $ADODB_INCLUDED_LIB;
if (!isset($force)) {
global $ADODB_FORCE_TYPE;
$force = $ADODB_FORCE_TYPE;
-
}
- if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+ if (empty($ADODB_INCLUDED_LIB)) {
+ include(ADODB_DIR.'/adodb-lib.inc.php');
+ }
return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
}
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
*/
-
- function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
- {
+ function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') {
return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
}
* $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
* $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
*/
- function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
- {
+ function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') {
$fd = fopen($path,'rb');
- if ($fd === false) return false;
+ if ($fd === false) {
+ return false;
+ }
$val = fread($fd,filesize($path));
fclose($fd);
return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
}
- function BlobDecode($blob)
- {
+ function BlobDecode($blob) {
return $blob;
}
- function BlobEncode($blob)
- {
+ function BlobEncode($blob) {
return $blob;
}
- function SetCharSet($charset)
- {
- return false;
+ function GetCharSet() {
+ return $this->charSet;
}
- function IfNull( $field, $ifNull )
- {
+ function SetCharSet($charset) {
+ $this->charSet = $charset;
+ return true;
+ }
+
+ function IfNull( $field, $ifNull ) {
return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
}
- function LogSQL($enable=true)
- {
+ function LogSQL($enable=true) {
include_once(ADODB_DIR.'/adodb-perf.inc.php');
- if ($enable) $this->fnExecute = 'adodb_log_sql';
- else $this->fnExecute = false;
+ if ($enable) {
+ $this->fnExecute = 'adodb_log_sql';
+ } else {
+ $this->fnExecute = false;
+ }
$old = $this->_logsql;
$this->_logsql = $enable;
- if ($enable && !$old) $this->_affected = false;
+ if ($enable && !$old) {
+ $this->_affected = false;
+ }
return $old;
}
- function GetCharSet()
- {
- return false;
- }
-
/**
* Usage:
* UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
* $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
* $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
*/
- function UpdateClob($table,$column,$val,$where)
- {
+ function UpdateClob($table,$column,$val,$where) {
return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
}
// not the fastest implementation - quick and dirty - jlim
// for best performance, use the actual $rs->MetaType().
- function MetaType($t,$len=-1,$fieldobj=false)
- {
+ function MetaType($t,$len=-1,$fieldobj=false) {
if (empty($this->_metars)) {
$rsclass = $this->rsPrefix.$this->databaseType;
* Change the SQL connection locale to a specified locale.
* This is used to get the date formats written depending on the client locale.
*/
- function SetDateLocale($locale = 'En')
- {
+ function SetDateLocale($locale = 'En') {
$this->locale = $locale;
switch (strtoupper($locale))
{
$extra=array(),
$relations=array())
{
- global $_ADODB_ACTIVE_DBS;
+ global $_ADODB_ACTIVE_DBS;
## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
- if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
+ if (!isset($_ADODB_ACTIVE_DBS)) {
+ include_once(ADODB_DIR.'/adodb-active-record.inc.php');
+ }
return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
}
- function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
- {
+ function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false) {
$arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
&