Upgraded ADOdb to 3.60 ... supposed to be faster plus has bugfixes

This commit is contained in:
moodler
2003-07-05 06:23:27 +00:00
parent 221518e109
commit 0d27c9ea8b
88 changed files with 26228 additions and 20633 deletions
File diff suppressed because it is too large Load Diff
+294 -294
View File
@@ -1,294 +1,294 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Made table name configurable - by David Johnson [email protected]
Encryption by Ari Kuorikoski <[email protected]>
Set tabs to 4 for best viewing.
Latest version of ADODB is available at http://php.weblogs.com/adodb
======================================================================
This file provides PHP4 session management using the ADODB database
wrapper library.
Example
=======
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
#---------------------------------#
include('adodb-cryptsession.php');
#---------------------------------#
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
Installation
============
1. Create a new database in MySQL or Access "sessions" like
so:
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
DATA text not null,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
3. Recommended is PHP 4.0.2 or later. There are documented
session bugs in
earlier versions of PHP.
*/
include_once('crypt.inc.php');
if (!defined('_ADODB_LAYER')) {
include ('adodb.inc.php');
}
if (!defined('ADODB_SESSION')) {
define('ADODB_SESSION',1);
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESS_DEBUG,
$ADODB_SESS_INSERT,
$ADODB_SESSION_EXPIRE_NOTIFY;
//$ADODB_SESS_DEBUG = true;
/* SET THE FOLLOWING PARAMETERS */
if (empty($ADODB_SESSION_DRIVER)) {
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='xphplens_2';
}
if (empty($ADODB_SESSION_TBL)){
$ADODB_SESSION_TBL = 'sessions';
}
if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
$ADODB_SESSION_EXPIRE_NOTIFY = false;
}
function ADODB_Session_Key()
{
$ADODB_CRYPT_KEY = 'CRYPTED ADODB SESSIONS ROCK!';
/* USE THIS FUNCTION TO CREATE THE ENCRYPTION KEY FOR CRYPTED SESSIONS */
/* Crypt the used key, $ADODB_CRYPT_KEY as key and session_ID as SALT */
return crypt($ADODB_CRYPT_KEY, session_ID());
}
$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
if ($ADODB_SESS_LIFE <= 1) {
// bug in PHP 4.0.3 pl 1 -- how about other versions?
//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
$ADODB_SESS_LIFE=1440;
}
function adodb_sess_open($save_path, $session_name)
{
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_DEBUG;
$ADODB_SESS_INSERT = false;
if (isset($ADODB_SESS_CONN)) return true;
$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
if (!empty($ADODB_SESS_DEBUG)) {
$ADODB_SESS_CONN->debug = true;
print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";
}
return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
}
function adodb_sess_close()
{
global $ADODB_SESS_CONN;
if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
return true;
}
function adodb_sess_read($key)
{
$Crypt = new MD5Crypt;
global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;
$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
if ($rs) {
if ($rs->EOF) {
$ADODB_SESS_INSERT = true;
$v = '';
} else {
// Decrypt session data
$v = rawurldecode($Crypt->Decrypt(reset($rs->fields), ADODB_Session_Key()));
}
$rs->Close();
return $v;
}
else $ADODB_SESS_INSERT = true;
return '';
}
function adodb_sess_write($key, $val)
{
$Crypt = new MD5Crypt;
global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
$expiry = time() + $ADODB_SESS_LIFE;
// encrypt session data..
$val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());
$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
global $$var;
$arr['expireref'] = $$var;
}
$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,
$arr,
'sesskey',$autoQuote = true);
if (!$rs) {
ADOConnection::outp( '<p>Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
} else {
// bug in access driver (could be odbc?) means that info is not commited
// properly unless select statement executed in Win2000
if ($ADODB_SESS_CONN->databaseType == 'access') $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
}
return isset($rs);
}
function adodb_sess_destroy($key)
{
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
$rs = $ADODB_SESS_CONN->Execute($qry);
}
return $rs ? true : false;
}
function adodb_sess_gc($maxlifetime) {
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
$ADODB_SESS_CONN->Execute($qry);
}
// suggested by Cameron, "GaM3R" <[email protected]>
if (defined('ADODB_SESSION_OPTIMIZE'))
{
switch( $ADODB_SESSION_DRIVER ) {
case 'mysql':
case 'mysqlt':
$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
break;
case 'postgresql':
case 'postgresql7':
$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;
break;
}
}
return true;
}
session_module_name('user');
session_set_save_handler(
"adodb_sess_open",
"adodb_sess_close",
"adodb_sess_read",
"adodb_sess_write",
"adodb_sess_destroy",
"adodb_sess_gc");
}
/* TEST SCRIPT -- UNCOMMENT */
/*
if (0) {
GLOBAL $HTTP_SESSION_VARS;
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
}
*/
?>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Made table name configurable - by David Johnson [email protected]
Encryption by Ari Kuorikoski <[email protected]>
Set tabs to 4 for best viewing.
Latest version of ADODB is available at http://php.weblogs.com/adodb
======================================================================
This file provides PHP4 session management using the ADODB database
wrapper library.
Example
=======
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
#---------------------------------#
include('adodb-cryptsession.php');
#---------------------------------#
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
Installation
============
1. Create a new database in MySQL or Access "sessions" like
so:
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
DATA text not null,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
3. Recommended is PHP 4.0.2 or later. There are documented
session bugs in
earlier versions of PHP.
*/
include_once('crypt.inc.php');
if (!defined('_ADODB_LAYER')) {
include ('adodb.inc.php');
}
if (!defined('ADODB_SESSION')) {
define('ADODB_SESSION',1);
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESS_DEBUG,
$ADODB_SESS_INSERT,
$ADODB_SESSION_EXPIRE_NOTIFY;
/* $ADODB_SESS_DEBUG = true; */
/* SET THE FOLLOWING PARAMETERS */
if (empty($ADODB_SESSION_DRIVER)) {
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='xphplens_2';
}
if (empty($ADODB_SESSION_TBL)){
$ADODB_SESSION_TBL = 'sessions';
}
if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
$ADODB_SESSION_EXPIRE_NOTIFY = false;
}
function ADODB_Session_Key()
{
$ADODB_CRYPT_KEY = 'CRYPTED ADODB SESSIONS ROCK!';
/* USE THIS FUNCTION TO CREATE THE ENCRYPTION KEY FOR CRYPTED SESSIONS */
/* Crypt the used key, $ADODB_CRYPT_KEY as key and session_ID as SALT */
return crypt($ADODB_CRYPT_KEY, session_ID());
}
$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
if ($ADODB_SESS_LIFE <= 1) {
/* bug in PHP 4.0.3 pl 1 -- how about other versions? */
/* print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>"; */
$ADODB_SESS_LIFE=1440;
}
function adodb_sess_open($save_path, $session_name)
{
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_DEBUG;
$ADODB_SESS_INSERT = false;
if (isset($ADODB_SESS_CONN)) return true;
$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
if (!empty($ADODB_SESS_DEBUG)) {
$ADODB_SESS_CONN->debug = true;
print" conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ";
}
return $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
}
function adodb_sess_close()
{
global $ADODB_SESS_CONN;
if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
return true;
}
function adodb_sess_read($key)
{
$Crypt = new MD5Crypt;
global $ADODB_SESS_CONN,$ADODB_SESS_INSERT,$ADODB_SESSION_TBL;
$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
if ($rs) {
if ($rs->EOF) {
$ADODB_SESS_INSERT = true;
$v = '';
} else {
/* Decrypt session data */
$v = rawurldecode($Crypt->Decrypt(reset($rs->fields), ADODB_Session_Key()));
}
$rs->Close();
return $v;
}
else $ADODB_SESS_INSERT = true;
return '';
}
function adodb_sess_write($key, $val)
{
$Crypt = new MD5Crypt;
global $ADODB_SESS_INSERT,$ADODB_SESS_CONN, $ADODB_SESS_LIFE, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
$expiry = time() + $ADODB_SESS_LIFE;
/* encrypt session data.. */
$val = $Crypt->Encrypt(rawurlencode($val), ADODB_Session_Key());
$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
global $$var;
$arr['expireref'] = $$var;
}
$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,
$arr,
'sesskey',$autoQuote = true);
if (!$rs) {
ADOConnection::outp( '<p>Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
} else {
/* bug in access driver (could be odbc?) means that info is not commited */
/* properly unless select statement executed in Win2000 */
if ($ADODB_SESS_CONN->databaseType == 'access') $rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
}
return isset($rs);
}
function adodb_sess_destroy($key)
{
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
$rs = $ADODB_SESS_CONN->Execute($qry);
}
return $rs ? true : false;
}
function adodb_sess_gc($maxlifetime) {
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
$ADODB_SESS_CONN->Execute($qry);
}
/* suggested by Cameron, "GaM3R" <[email protected]> */
if (defined('ADODB_SESSION_OPTIMIZE'))
{
switch( $ADODB_SESSION_DRIVER ) {
case 'mysql':
case 'mysqlt':
$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
break;
case 'postgresql':
case 'postgresql7':
$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;
break;
}
}
return true;
}
session_module_name('user');
session_set_save_handler(
"adodb_sess_open",
"adodb_sess_close",
"adodb_sess_read",
"adodb_sess_write",
"adodb_sess_destroy",
"adodb_sess_gc");
}
/* TEST SCRIPT -- UNCOMMENT */
/*
if (0) {
GLOBAL $HTTP_SESSION_VARS;
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
}
*/
?>
+217 -228
View File
@@ -1,229 +1,218 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Library for CSV serialization. This is used by the csv/proxy driver and is the
CacheExecute() serialization format.
==== NOTE ====
Format documented at http://php.weblogs.com/ADODB_CSV
==============
*/
/**
* convert a recordset into special format
*
* @param rs the recordset
*
* @return the CSV formated data
*/
function _rs2serialize(&$rs,$conn=false,$sql='')
{
$max = ($rs) ? $rs->FieldCount() : 0;
if ($sql) $sql = urlencode($sql);
// metadata setup
if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
if (is_object($conn)) {
$sql .= ','.$conn->Affected_Rows();
$sql .= ','.$conn->Insert_ID();
} else
$sql .= ',,';
$text = "====-1,0,$sql\n";
return $text;
} else {
$tt = ($rs->timeCreated) ? $rs->timeCreated : time();
$line = "====0,$tt,$sql\n";
}
// column definitions
for($i=0; $i < $max; $i++) {
$o = $rs->FetchField($i);
$line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length).":$o->max_length,";
}
$text = substr($line,0,strlen($line)-1)."\n";
// get data
if ($rs->databaseType == 'array') {
$text .= serialize($rs->_array);
} else {
$rows = array();
while (!$rs->EOF) {
$rows[] = $rs->fields;
$rs->MoveNext();
}
$text .= serialize($rows);
}
$rs->MoveFirst();
return $text;
}
/**
* Open CSV file and convert it into Data.
*
* @param url file/ftp/http url
* @param err returns the error message
* @param timeout dispose if recordset has been alive for $timeout secs
*
* @return recordset, or false if error occured. If no
* error occurred in sql INSERT/UPDATE/DELETE,
* empty recordset is returned
*/
function &csv2rs($url,&$err,$timeout=0)
{
$ishttp = strpos(substr($url,3,10),':') !== false;
$fp = @fopen($url,'r');
$err = false;
if (!$fp) {
$err = $url.'file/URL not found';
return false;
}
if (!$ishttp) flock($fp, LOCK_SH);
$arr = array();
$ttl = 0;
if ($meta = fgetcsv($fp, 32000, ",")) { // first read is larger because contains sql
// check if error message
if (strncmp($meta[0],'****',4) === 0) {
$err = trim(substr($meta[0],4,1024));
fclose($fp);
return false;
}
// check for meta data
// $meta[0] is -1 means return an empty recordset
// $meta[1] contains a time
if (strncmp($meta[0],'====',4) === 0) {
if ($meta[0] == "====-1") {
if (sizeof($meta) < 5) {
$err = "Corrupt first line for format -1";
fclose($fp);
return false;
}
fclose($fp);
if ($timeout > 0) {
$err = " Illegal Timeout $timeout ";
return false;
}
$rs->fields = array();
$rs->timeCreated = $meta[1];
$rs = new ADORecordSet($val=true);
$rs->EOF = true;
$rs->_numOfFields=0;
$rs->sql = urldecode($meta[2]);
$rs->affectedrows = (integer)$meta[3];
$rs->insertid = $meta[4];
return $rs;
}
# If detect timeout here return false, forcing a fresh query and new cache values
#
# Under high volume loads, we want only 1 thread/process to _write_file
# so that we don't have 50 processes queueing to write the same data.
#
# We implement a probabilistic blocking write:
#
# -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io
# -1 sec after timeout give processes 1/4 chance of writing with blocking
# +0 sec after timeout, give processes 100% chance writing with blocking
if (sizeof($meta) > 1) {
if($timeout >0){
$tdiff = $meta[1]+$timeout - time();
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 0xf) == 0) {
fclose($fp);
$err = "Timeout 2";
return false;
}
break;
case 1:
if ((rand() & 0x3) == 0) {
fclose($fp);
$err = "Timeout 1";
return false;
}
break;
default:
fclose($fp);
$err = "Timeout 0";
return false;
} // switch
} // if check flush cache
}// (timeout>0)
$ttl = $meta[1];
}
$meta = false;
$meta = fgetcsv($fp, 16000, ",");
if (!$meta) {
fclose($fp);
$err = "Unexpected EOF 1";
return false;
}
}
// Get Column definitions
$flds = array();
foreach($meta as $o) {
$o2 = explode(':',$o);
if (sizeof($o2)!=3) {
$arr[] = $meta;
$flds = false;
break;
}
$fld = new ADOFieldObject();
$fld->name = urldecode($o2[0]);
$fld->type = $o2[1];
$fld->max_length = $o2[2];
$flds[] = $fld;
}
} else {
fclose($fp);
$err = "Recordset had unexpected EOF 2";
return false;
}
// slurp in the data
$MAXSIZE = 128000;
$text = fread($fp,$MAXSIZE);
$cnt = 1;
while (strlen($text) == $MAXSIZE*$cnt) {
$text .= fread($fp,$MAXSIZE);
$cnt += 1;
}
fclose($fp);
//print "<hr>";
//print_r($text);
//if (strlen($text) == 0) $arr = array();
//else
$arr = unserialize($text);
//print_r($arr);
if (!is_array($arr)) {
$err = "Recordset had unexpected EOF (in serialized recordset)";
if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
return false;
}
$rs = new ADORecordSet_array();
$rs->timeCreated = $ttl;
$rs->InitArrayFields($arr,$flds);
return $rs;
}
<?php
/*
V2.50 14 Nov 2002 (c) 2000-2002 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Library for CSV serialization. This is used by the csv/proxy driver and is the
CacheExecute() serialization format.
==== NOTE ====
Format documented at http://php.weblogs.com/ADODB_CSV
==============
*/
/**
* convert a recordset into special format
*
* @param rs the recordset
*
* @return the CSV formated data
*/
function _rs2serialize(&$rs,$conn=false,$sql='')
{
$max = ($rs) ? $rs->FieldCount() : 0;
if ($sql) $sql = urlencode($sql);
/* metadata setup */
if ($max <= 0 || $rs->dataProvider == 'empty') { /* is insert/update/delete */
if (is_object($conn)) {
$sql .= ','.$conn->Affected_Rows();
$sql .= ','.$conn->Insert_ID();
} else
$sql .= ',,';
$text = "====-1,0,$sql\n";
return $text;
} else {
$tt = ($rs->timeCreated) ? $rs->timeCreated : time();
$line = "====0,$tt,$sql\n";
}
/* column definitions */
for($i=0; $i < $max; $i++) {
$o = $rs->FetchField($i);
$line .= urlencode($o->name).':'.$rs->MetaType($o->type,$o->max_length).":$o->max_length,";
}
$text = substr($line,0,strlen($line)-1)."\n";
/* get data */
if ($rs->databaseType == 'array') {
$text .= serialize($rs->_array);
} else {
$rows = array();
while (!$rs->EOF) {
$rows[] = $rs->fields;
$rs->MoveNext();
}
$text .= serialize($rows);
}
$rs->MoveFirst();
return $text;
}
/**
* Open CSV file and convert it into Data.
*
* @param url file/ftp/http url
* @param err returns the error message
* @param timeout dispose if recordset has been alive for $timeout secs
*
* @return recordset, or false if error occured. If no
* error occurred in sql INSERT/UPDATE/DELETE,
* empty recordset is returned
*/
function &csv2rs($url,&$err,$timeout=0)
{
$fp = @fopen($url,'r');
$err = false;
if (!$fp) {
$err = $url.'file/URL not found';
return false;
}
flock($fp, LOCK_SH);
$arr = array();
$ttl = 0;
if ($meta = fgetcsv ($fp, 32000, ",")) {
/* check if error message */
if (substr($meta[0],0,4) === '****') {
$err = trim(substr($meta[0],4,1024));
fclose($fp);
return false;
}
/* check for meta data */
/* $meta[0] is -1 means return an empty recordset */
/* $meta[1] contains a time */
if (substr($meta[0],0,4) === '====') {
if ($meta[0] == "====-1") {
if (sizeof($meta) < 5) {
$err = "Corrupt first line for format -1";
fclose($fp);
return false;
}
fclose($fp);
if ($timeout > 0) {
$err = " Illegal Timeout $timeout ";
return false;
}
$rs->fields = array();
$rs->timeCreated = $meta[1];
$rs = new ADORecordSet($val=true);
$rs->EOF = true;
$rs->_numOfFields=0;
$rs->sql = urldecode($meta[2]);
$rs->affectedrows = (integer)$meta[3];
$rs->insertid = $meta[4];
return $rs;
}
# Under high volume loads, we want only 1 thread/process to _write_file
# so that we don't have 50 processes queueing to write the same data.
# Would require probabilistic blocking write
#
# -2 sec before timeout, give processes 1/16 chance of writing to file with blocking io
# -1 sec after timeout give processes 1/4 chance of writing with blocking
# +0 sec after timeout, give processes 100% chance writing with blocking
if (sizeof($meta) > 1) {
if($timeout >0){
$tdiff = $meta[1]+$timeout - time();
if ($tdiff <= 2) {
switch($tdiff) {
case 2:
if ((rand() & 15) == 0) {
fclose($fp);
$err = "Timeout 2";
return false;
}
break;
case 1:
if ((rand() & 3) == 0) {
fclose($fp);
$err = "Timeout 1";
return false;
}
break;
default:
fclose($fp);
$err = "Timeout 0";
return false;
} /* switch */
} /* if check flush cache */
}/* (timeout>0) */
$ttl = $meta[1];
}
$meta = false;
$meta = fgetcsv($fp, 16000, ",");
if (!$meta) {
fclose($fp);
$err = "Unexpected EOF 1";
return false;
}
}
/* Get Column definitions */
$flds = array();
foreach($meta as $o) {
$o2 = explode(':',$o);
if (sizeof($o2)!=3) {
$arr[] = $meta;
$flds = false;
break;
}
$fld = new ADOFieldObject();
$fld->name = urldecode($o2[0]);
$fld->type = $o2[1];
$fld->max_length = $o2[2];
$flds[] = $fld;
}
} else {
fclose($fp);
$err = "Recordset had unexpected EOF 2";
return false;
}
/* slurp in the data */
$MAXSIZE = 128000;
$text = fread($fp,$MAXSIZE);
$cnt = 1;
while (strlen($text) == $MAXSIZE*$cnt) {
$text .= fread($fp,$MAXSIZE);
$cnt += 1;
}
fclose($fp);
$arr = @unserialize($text);
/* var_dump($arr); */
if (!is_array($arr)) {
$err = "Recordset had unexpected EOF (in serialized recordset)";
if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!";
return false;
}
$rs = new ADORecordSet_array();
$rs->timeCreated = $ttl;
$rs->InitArrayFields($arr,$flds);
return $rs;
}
?>
+581 -331
View File
@@ -1,332 +1,582 @@
<?php
/**
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
DOCUMENTATION:
See adodb/tests/test-datadict.php for docs and examples.
*/
class ADODB_DataDict {
var $connection;
var $debug = false;
var $dropTable = "DROP TABLE %s";
var $addCol = ' ADD';
var $alterCol = ' ALTER COLUMN';
var $dropCol = ' DROP COLUMN';
var $schema = false;
var $serverInfo = array();
function MetaTables()
{
return $this->connection->MetaTables();
}
function MetaColumns($tab)
{
return $this->connection->MetaColumns($tab);
}
function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
{
return $this->connection->MetaPrimaryKeys($tab.$owner,$intkey);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
return ADORecordSet::MetaType($t,$len,$fieldobj);
}
// Executes the sql array returned by GetTableSQL and GetIndexSQL
function ExecuteSQLArray($sql, $continueOnError = true)
{
$rez = 2;
$conn = &$this->connection;
foreach($sql as $line) {
$ok = $conn->Execute($line);
if (!$ok) {
if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
if (!$continueOnError) return 0;
$rez = 1;
}
}
return 2;
}
/*
Returns the actual type given a character code.
C: varchar
X: CLOB (character large object) or largest varchar size if CLOB is not supported
C2: Multibyte varchar
X2: Multibyte CLOB
B: BLOB (binary large object)
D: Date
T: Date-time
L: Integer field suitable for storing booleans (0 or 1)
I: Integer
F: Floating point number
N: Numeric or decimal number
*/
function ActualType($meta)
{
return $meta;
}
function CreateDatabase($dbname,$options=false)
{
$options = $this->_Options($options);
$s = 'CREATE DATABASE '.$dbname;
if (isset($options[$this->upperName])) $s .= ' '.$options[$this->upperName];
$sql[] = $s;
return $sql;
}
/*
Generates the SQL to create index. Returns an array of sql strings.
*/
function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
return $this->_IndexSQL($idxname, $tabname, $flds, $this->_Options($idxoptions));
}
function SetSchema($schema)
{
$this->schema = $schema;
}
function AddColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->addCol $v";
}
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
if (!is_array($flds)) $flds = explode(',',$flds);
$sql = array();
foreach($flds as $v) {
$sql[] = "ALTER TABLE $tabname $this->dropCol $v";
}
return $sql;
}
function DropTableSQL($tabname)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql[] = sprintf($this->dropTable,$tabname);
return $sql;
}
/*
Generate the SQL to create table. Returns an array of sql strings.
*/
function CreateTableSQL($tabname, $flds, $tableoptions=false)
{
if (!$tableoptions) $tableoptions = array();
list($lines,$pkey) = $this->_GenFields($flds);
$taboptions = $this->_Options($tableoptions);
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
$tsql = $this->_Triggers($tabname,$taboptions);
foreach($tsql as $s) $sql[] = $s;
return $sql;
}
function _GenFields($flds)
{
$lines = array();
$pkey = array();
foreach($flds as $fld) {
$fld = _array_change_key_case($fld);
$fname = false;
$fdefault = false;
$fautoinc = false;
$ftype = false;
$fsize = false;
$fprec = false;
$fprimary = false;
$fnoquote = false;
$fdefts = false;
$fdefdate = false;
$fconstraint = false;
$fnotnull = false;
//-----------------
// Parse attributes
foreach($fld as $attr => $v) {
if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
switch($attr) {
case '0':
case 'NAME': $fname = $v; break;
case '1':
case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
case 'SIZE': $dotat = strpos($v,'.');
if ($dotat === false) $fsize = $v;
else {
$fsize = substr($v,0,$dotat);
$fprec = substr($v,$dotat+1);
}
break;
case 'AUTOINCREMENT':
case 'AUTO': $fautoinc = true; $fnotnull = true; break;
case 'KEY':
case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;
case 'DEFAULT': $fdefault = $v; break;
case 'NOTNULL': $fnotnull = $v; break;
case 'NOQUOTE': $fnoquote = $v; break;
case 'DEFDATE': $fdefdate = $v; break;
case 'DEFTIMESTAMP': $fdefts = $v; break;
case 'CONSTRAINT': $fconstraint = $v; break;
} //switch
} // foreach $fld
//--------------------
// VALIDATE FIELD INFO
if (!strlen($fname)) {
if ($this->debug) ADOConnection::outp("Undefined NAME");
return false;
}
if (!strlen($ftype)) {
if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
return false;
} else
$ftype = strtoupper($ftype);
$ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
if ($fprimary) $pkey[] = $fname;
// some databases do not allow blobs to have defaults
if ($ty == 'X') $fdefault = false;
//--------------------
// CONSTRUCT FIELD SQL
if ($fdefts) {
if (substr($this->connection->databaseType,0,5) == 'mysql') {
$ftype = 'TIMESTAMP';
} else {
$fdefault = $this->connection->sysTimeStamp;
}
} else if ($fdefdate) {
if (substr($this->connection->databaseType,0,5) == 'mysql') {
$ftype = 'TIMESTAMP';
} else {
$fdefault = $this->connection->sysDate;
}
} else if (strlen($fdefault) && !$fnoquote)
if ($ty == 'C' or $ty == 'X' or
( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
if (substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
$fdefault = trim($fdefault);
else
$fdefault = $this->connection->qstr($fdefault);
$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint);
$fname = str_pad($fname,16);
$lines[] = "$fname $ftype$suffix";
} // foreach $flds
return array($lines,$pkey);
}
/*
GENERATE THE SIZE PART OF THE DATATYPE
$ftype is the actual type
$ty is the type defined originally in the DDL
*/
function _GetSize($ftype, $ty, $fsize, $fprec)
{
if (strlen($fsize) && $ty != 'X' && $ty != 'B') {
$ftype .= "(".$fsize;
if ($fprec) $ftype .= ",".$fprec;
$ftype .= ')';
}
return $ftype;
}
function _TableSQL($tabname,$lines,$pkey,$tableoptions)
{
$sql = array();
if (isset($tableoptions['REPLACE'])) $sql[] = sprintf($this->dropTable,$tabname);
$s = "CREATE TABLE $tabname (\n";
$s .= implode(",\n", $lines);
if (sizeof($pkey)>0) {
$s .= ",\n PRIMARY KEY (";
$s .= implode(", ",$pkey).")";
}
if (isset($tableoptions['CONSTRAINTS']))
$s .= "\n".$tableoptions['CONSTRAINTS'];
if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
$s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
$s .= "\n)";
if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
/*
GENERATE TRIGGERS IF NEEDED
used when table has auto-incrementing field that is emulated using triggers
*/
function _Triggers($tabname,$taboptions)
{
return array();
}
/*
Sanitize options, so that array elements with no keys are promoted to keys
*/
function _Options($opts)
{
if (!is_array($opts)) return array();
$newopts = array();
foreach($opts as $k => $v) {
if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
else $newopts[strtoupper($k)] = $v;
}
return $newopts;
}
}
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
DOCUMENTATION:
See adodb/tests/test-datadict.php for docs and examples.
*/
/*
Test script for parser
*/
function Lens_ParseTest()
{
$str = "ACOL NUMBER(32,2) DEFAULT 'The \"cow\" (and Jim''s dog) jumps over the moon' PRIMARY, INTI INT AUTO DEFAULT 0";
print "<p>$str</p>";
$a= Lens_ParseArgs($str);
print "<pre>";
print_r($a);
print "</pre>";
}
/* Lens_ParseTest(); */
/**
Parse arguments, treat "text" (text) and 'text' as quotation marks.
To escape, use "" or '' or ))
@param endstmtchar Character that indicates end of statement
@param tokenchars Include the following characters in tokens apart from A-Z and 0-9
@returns 2 dimensional array containing parsed tokens.
*/
function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
{
$pos = 0;
$intoken = false;
$stmtno = 0;
$endquote = false;
$tokens = array();
$tokens[$stmtno] = array();
$max = strlen($args);
$quoted = false;
while ($pos < $max) {
$ch = substr($args,$pos,1);
switch($ch) {
case ' ':
case "\t":
case "\n":
case "\r":
if (!$quoted) {
if ($intoken) {
$intoken = false;
$tokens[$stmtno][] = implode('',$tokarr);
}
break;
}
$tokarr[] = $ch;
break;
case '(':
case ')':
case '"':
case "'":
if ($intoken) {
if (empty($endquote)) {
$tokens[$stmtno][] = implode('',$tokarr);
if ($ch == '(') $endquote = ')';
else $endquote = $ch;
$quoted = true;
$intoken = true;
$tokarr = array();
} else if ($endquote == $ch) {
$ch2 = substr($args,$pos+1,1);
if ($ch2 == $endquote) {
$pos += 1;
$tokarr[] = $ch2;
} else {
$quoted = false;
$intoken = false;
$tokens[$stmtno][] = implode('',$tokarr);
$endquote = '';
}
} else
$tokarr[] = $ch;
}else {
if ($ch == '(') $endquote = ')';
else $endquote = $ch;
$quoted = true;
$intoken = true;
$tokarr = array();
}
break;
default:
if (!$intoken) {
if ($ch == $endstmtchar) {
$stmtno += 1;
$tokens[$stmtno] = array();
break;
}
$intoken = true;
$quoted = false;
$endquote = false;
$tokarr = array();
}
if ($quoted) $tokarr[] = $ch;
else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
else {
if ($ch == $endstmtchar) {
$tokens[$stmtno][] = implode('',$tokarr);
$stmtno += 1;
$tokens[$stmtno] = array();
$intoken = false;
$tokarr = array();
break;
}
$tokens[$stmtno][] = implode('',$tokarr);
$tokens[$stmtno][] = $ch;
$intoken = false;
}
}
$pos += 1;
}
return $tokens;
}
class ADODB_DataDict {
var $connection;
var $debug = false;
var $dropTable = "DROP TABLE %s";
var $addCol = ' ADD';
var $alterCol = ' ALTER COLUMN';
var $dropCol = ' DROP COLUMN';
var $schema = false;
var $serverInfo = array();
var $autoIncrement = false;
var $dataProvider;
var $blobSize = 100; /* / any varchar/char field this size or greater is treated as a blob */
/* / in other words, we use a text area for editting. */
function GetCommentSQL($table,$col)
{
return false;
}
function SetCommentSQL($table,$col,$cmt)
{
return false;
}
function &MetaTables()
{
return $this->connection->MetaTables();
}
function &MetaColumns($tab)
{
return $this->connection->MetaColumns($tab);
}
function &MetaPrimaryKeys($tab,$owner=false,$intkey=false)
{
return $this->connection->MetaPrimaryKeys($tab.$owner,$intkey);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
return ADORecordSet::MetaType($t,$len,$fieldobj);
}
/* Executes the sql array returned by GetTableSQL and GetIndexSQL */
function ExecuteSQLArray($sql, $continueOnError = true)
{
$rez = 2;
$conn = &$this->connection;
$saved = $conn->debug;
foreach($sql as $line) {
if ($this->debug) $conn->debug = true;
$ok = $conn->Execute($line);
$conn->debug = $saved;
if (!$ok) {
if ($this->debug) ADOConnection::outp($conn->ErrorMsg());
if (!$continueOnError) return 0;
$rez = 1;
}
}
return 2;
}
/*
Returns the actual type given a character code.
C: varchar
X: CLOB (character large object) or largest varchar size if CLOB is not supported
C2: Multibyte varchar
X2: Multibyte CLOB
B: BLOB (binary large object)
D: Date
T: Date-time
L: Integer field suitable for storing booleans (0 or 1)
I: Integer
F: Floating point number
N: Numeric or decimal number
*/
function ActualType($meta)
{
return $meta;
}
function CreateDatabase($dbname,$options=false)
{
$options = $this->_Options($options);
$s = 'CREATE DATABASE '.$dbname;
if (isset($options[$this->upperName])) $s .= ' '.$options[$this->upperName];
$sql[] = $s;
return $sql;
}
/*
Generates the SQL to create index. Returns an array of sql strings.
*/
function CreateIndexSQL($idxname, $tabname, $flds, $idxoptions = false)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
return $this->_IndexSQL($idxname, $tabname, $flds, $this->_Options($idxoptions));
}
function SetSchema($schema)
{
$this->schema = $schema;
}
function AddColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->addCol $v";
}
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
if (!is_array($flds)) $flds = explode(',',$flds);
$sql = array();
foreach($flds as $v) {
$sql[] = "ALTER TABLE $tabname $this->dropCol $v";
}
return $sql;
}
function DropTableSQL($tabname)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql[] = sprintf($this->dropTable,$tabname);
return $sql;
}
/*
Generate the SQL to create table. Returns an array of sql strings.
*/
function CreateTableSQL($tabname, $flds, $tableoptions=false)
{
if (!$tableoptions) $tableoptions = array();
list($lines,$pkey) = $this->_GenFields($flds);
$taboptions = $this->_Options($tableoptions);
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
$tsql = $this->_Triggers($tabname,$taboptions);
foreach($tsql as $s) $sql[] = $s;
return $sql;
}
function _GenFields($flds)
{
if (is_string($flds)) {
$padding = ' ';
$txt = $flds.$padding;
$flds = array();
$flds0 = Lens_ParseArgs($txt,',');
$hasparam = false;
foreach($flds0 as $f0) {
$f1 = array();
foreach($f0 as $token) {
switch (strtoupper($token)) {
case 'CONSTRAINT':
case 'DEFAULT':
$hasparam = $token;
break;
default:
if ($hasparam) $f1[$hasparam] = $token;
else $f1[] = $token;
$hasparam = false;
break;
}
}
$flds[] = $f1;
}
}
$this->autoIncrement = false;
$lines = array();
$pkey = array();
foreach($flds as $fld) {
$fld = _array_change_key_case($fld);
$fname = false;
$fdefault = false;
$fautoinc = false;
$ftype = false;
$fsize = false;
$fprec = false;
$fprimary = false;
$fnoquote = false;
$fdefts = false;
$fdefdate = false;
$fconstraint = false;
$fnotnull = false;
$funsigned = false;
/* ----------------- */
/* Parse attributes */
foreach($fld as $attr => $v) {
if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
switch($attr) {
case '0':
case 'NAME': $fname = $v; break;
case '1':
case 'TYPE': $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
case 'SIZE': $dotat = strpos($v,'.');
if ($dotat === false) $fsize = $v;
else {
$fsize = substr($v,0,$dotat);
$fprec = substr($v,$dotat+1);
}
break;
case 'UNSIGNED': $funsigned = true; break;
case 'AUTOINCREMENT':
case 'AUTO': $fautoinc = true; $fnotnull = true; break;
case 'KEY':
case 'PRIMARY': $fprimary = $v; $fnotnull = true; break;
case 'DEF':
case 'DEFAULT': $fdefault = $v; break;
case 'NOTNULL': $fnotnull = $v; break;
case 'NOQUOTE': $fnoquote = $v; break;
case 'DEFDATE': $fdefdate = $v; break;
case 'DEFTIMESTAMP': $fdefts = $v; break;
case 'CONSTRAINT': $fconstraint = $v; break;
} /* switch */
} /* foreach $fld */
/* -------------------- */
/* VALIDATE FIELD INFO */
if (!strlen($fname)) {
if ($this->debug) ADOConnection::outp("Undefined NAME");
return false;
}
if (!strlen($ftype)) {
if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
return false;
} else {
$ftype = strtoupper($ftype);
}
$ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; /* some blob types do not accept nulls */
if ($fprimary) $pkey[] = $fname;
/* some databases do not allow blobs to have defaults */
if ($ty == 'X') $fdefault = false;
/* -------------------- */
/* CONSTRUCT FIELD SQL */
if ($fdefts) {
if (substr($this->connection->databaseType,0,5) == 'mysql') {
$ftype = 'TIMESTAMP';
} else {
$fdefault = $this->connection->sysTimeStamp;
}
} else if ($fdefdate) {
if (substr($this->connection->databaseType,0,5) == 'mysql') {
$ftype = 'TIMESTAMP';
} else {
$fdefault = $this->connection->sysDate;
}
} else if (strlen($fdefault) && !$fnoquote)
if ($ty == 'C' or $ty == 'X' or
( substr($fdefault,0,1) != "'" && !is_numeric($fdefault)))
if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
$fdefault = trim($fdefault);
else if (strtolower($fdefault) != 'null')
$fdefault = $this->connection->qstr($fdefault);
$suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
$fname = str_pad($fname,16);
$lines[] = "$fname $ftype$suffix";
if ($fautoinc) $this->autoIncrement = true;
} /* foreach $flds */
return array($lines,$pkey);
}
/*
GENERATE THE SIZE PART OF THE DATATYPE
$ftype is the actual type
$ty is the type defined originally in the DDL
*/
function _GetSize($ftype, $ty, $fsize, $fprec)
{
if (strlen($fsize) && $ty != 'X' && $ty != 'B' && strpos($ftype,'(') === false) {
$ftype .= "(".$fsize;
if ($fprec) $ftype .= ",".$fprec;
$ftype .= ')';
}
return $ftype;
}
/* return string must begin with space */
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$s .= "($flds)";
$sql[] = $s;
return $sql;
}
function _DropAutoIncrement($tabname)
{
return false;
}
function _TableSQL($tabname,$lines,$pkey,$tableoptions)
{
$sql = array();
if (isset($tableoptions['REPLACE'])) {
$sql[] = sprintf($this->dropTable,$tabname);
if ($this->autoIncrement) {
$sInc = $this->_DropAutoIncrement($tabname);
if ($sInc) $sql[] = $sInc;
}
}
$s = "CREATE TABLE $tabname (\n";
$s .= implode(",\n", $lines);
if (sizeof($pkey)>0) {
$s .= ",\n PRIMARY KEY (";
$s .= implode(", ",$pkey).")";
}
if (isset($tableoptions['CONSTRAINTS']))
$s .= "\n".$tableoptions['CONSTRAINTS'];
if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
$s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
$s .= "\n)";
if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
/*
GENERATE TRIGGERS IF NEEDED
used when table has auto-incrementing field that is emulated using triggers
*/
function _Triggers($tabname,$taboptions)
{
return array();
}
/*
Sanitize options, so that array elements with no keys are promoted to keys
*/
function _Options($opts)
{
if (!is_array($opts)) return array();
$newopts = array();
foreach($opts as $k => $v) {
if (is_numeric($k)) $newopts[strtoupper($v)] = $v;
else $newopts[strtoupper($k)] = $v;
}
return $newopts;
}
/*
"Florian Buzin [ easywe ]" <[email protected]>
This function changes/adds new fields to your table. You
dont have to know if the col is new or not. It will check on its
own.
*/
function ChangeTableSQL($tablename, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tablename;
else $tabname = $tablename;
$conn = &$this->connection;
if (!$conn) return false;
$colarr = $conn->MetaColumns($tabname);
if (!$colarr) return $this->CreateTableSQL($tablename,$flds);
foreach($colarr as $col) $cols[strtoupper($col->name)] = " ALTER ";
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$f = explode(" ",$v);
if(!empty($cols[strtoupper($f[0])])){
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}else{
$sql[] = "ALTER TABLE $tabname $this->addCol $v";
}
}
return $sql;
}
} /* class */
?>
+237 -263
View File
@@ -1,264 +1,238 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* The following code is adapted from the PEAR DB error handling code.
* Portions (c)1997-2002 The PHP Group.
*/
if (!defined("DB_ERROR")) define("DB_ERROR",-1);
if (!defined("DB_ERROR_SYNTAX")) {
define("DB_ERROR_SYNTAX", -2);
define("DB_ERROR_CONSTRAINT", -3);
define("DB_ERROR_NOT_FOUND", -4);
define("DB_ERROR_ALREADY_EXISTS", -5);
define("DB_ERROR_UNSUPPORTED", -6);
define("DB_ERROR_MISMATCH", -7);
define("DB_ERROR_INVALID", -8);
define("DB_ERROR_NOT_CAPABLE", -9);
define("DB_ERROR_TRUNCATED", -10);
define("DB_ERROR_INVALID_NUMBER", -11);
define("DB_ERROR_INVALID_DATE", -12);
define("DB_ERROR_DIVZERO", -13);
define("DB_ERROR_NODBSELECTED", -14);
define("DB_ERROR_CANNOT_CREATE", -15);
define("DB_ERROR_CANNOT_DELETE", -16);
define("DB_ERROR_CANNOT_DROP", -17);
define("DB_ERROR_NOSUCHTABLE", -18);
define("DB_ERROR_NOSUCHFIELD", -19);
define("DB_ERROR_NEED_MORE_DATA", -20);
define("DB_ERROR_NOT_LOCKED", -21);
define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
define("DB_ERROR_INVALID_DSN", -23);
define("DB_ERROR_CONNECT_FAILED", -24);
define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
define("DB_ERROR_NOSUCHDB", -25);
define("DB_ERROR_ACCESS_VIOLATION", -26);
}
function adodb_errormsg($value)
{
static $ERRMSG;
if (!isset($ERRMSG)) {
$ERRMSG = array(
DB_ERROR => 'unknown error',
DB_ERROR_ALREADY_EXISTS => 'already exists',
DB_ERROR_CANNOT_CREATE => 'can not create',
DB_ERROR_CANNOT_DELETE => 'can not delete',
DB_ERROR_CANNOT_DROP => 'can not drop',
DB_ERROR_CONSTRAINT => 'constraint violation',
DB_ERROR_DIVZERO => 'division by zero',
DB_ERROR_INVALID => 'invalid',
DB_ERROR_INVALID_DATE => 'invalid date or time',
DB_ERROR_INVALID_NUMBER => 'invalid number',
DB_ERROR_MISMATCH => 'mismatch',
DB_ERROR_NODBSELECTED => 'no database selected',
DB_ERROR_NOSUCHFIELD => 'no such field',
DB_ERROR_NOSUCHTABLE => 'no such table',
DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
DB_ERROR_NOT_FOUND => 'not found',
DB_ERROR_NOT_LOCKED => 'not locked',
DB_ERROR_SYNTAX => 'syntax error',
DB_ERROR_UNSUPPORTED => 'not supported',
DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
DB_ERROR_INVALID_DSN => 'invalid DSN',
DB_ERROR_CONNECT_FAILED => 'connect failed',
0 => 'no error', // DB_OK
DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
DB_ERROR_NOSUCHDB => 'no such database',
DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions'
);
}
return isset($ERRMSG[$value]) ? $ERRMSG[$value] : $ERRMSG[DB_ERROR];
}
function adodb_error($provider,$dbType,$errno)
{
var_dump($errno);
if (is_numeric($errno) && $errno == 0) return 0;
switch($provider) {
case 'mysql': $map = adodb_error_mysql(); break;
case 'oracle':
case 'oci8': $map = adodb_error_oci8(); break;
case 'ibase': $map = adodb_error_ibase(); break;
case 'odbc': $map = adodb_error_odbc(); break;
case 'mssql':
case 'sybase': $map = adodb_error_mssql(); break;
case 'informix': $map = adodb_error_ifx(); break;
case 'postgres': return adodb_error_pg($errno); break;
default:
return DB_ERROR;
}
print_r($map);
var_dump($errno);
if (isset($map[$errno])) return $map[$errno];
return DB_ERROR;
}
//**************************************************************************************
function adodb_error_pg($errormsg)
{
static $error_regexps = array(
'/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS,
'/divide by zero$/' => DB_ERROR_DIVZERO,
'/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
'/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
'/parser: parse error at or near \"/' => DB_ERROR_SYNTAX,
'/referential integrity violation/' => DB_ERROR_CONSTRAINT
);
foreach ($error_regexps as $regexp => $code) {
if (preg_match($regexp, $errormsg)) {
return $code;
}
}
// Fall back to DB_ERROR if there was no mapping.
return DB_ERROR;
}
function adodb_error_odbc()
{
static $MAP = array(
'01004' => DB_ERROR_TRUNCATED,
'07001' => DB_ERROR_MISMATCH,
'21S01' => DB_ERROR_MISMATCH,
'21S02' => DB_ERROR_MISMATCH,
'22003' => DB_ERROR_INVALID_NUMBER,
'22008' => DB_ERROR_INVALID_DATE,
'22012' => DB_ERROR_DIVZERO,
'23000' => DB_ERROR_CONSTRAINT,
'24000' => DB_ERROR_INVALID,
'34000' => DB_ERROR_INVALID,
'37000' => DB_ERROR_SYNTAX,
'42000' => DB_ERROR_SYNTAX,
'IM001' => DB_ERROR_UNSUPPORTED,
'S0000' => DB_ERROR_NOSUCHTABLE,
'S0001' => DB_ERROR_NOT_FOUND,
'S0002' => DB_ERROR_NOSUCHTABLE,
'S0011' => DB_ERROR_ALREADY_EXISTS,
'S0012' => DB_ERROR_NOT_FOUND,
'S0021' => DB_ERROR_ALREADY_EXISTS,
'S0022' => DB_ERROR_NOT_FOUND,
'S1000' => DB_ERROR_NOSUCHTABLE,
'S1009' => DB_ERROR_INVALID,
'S1090' => DB_ERROR_INVALID,
'S1C00' => DB_ERROR_NOT_CAPABLE
);
return $MAP;
}
function adodb_error_ibase()
{
static $MAP = array(
-104 => DB_ERROR_SYNTAX,
-150 => DB_ERROR_ACCESS_VIOLATION,
-151 => DB_ERROR_ACCESS_VIOLATION,
-155 => DB_ERROR_NOSUCHTABLE,
-157 => DB_ERROR_NOSUCHFIELD,
-158 => DB_ERROR_VALUE_COUNT_ON_ROW,
-170 => DB_ERROR_MISMATCH,
-171 => DB_ERROR_MISMATCH,
-172 => DB_ERROR_INVALID,
-204 => DB_ERROR_INVALID,
-205 => DB_ERROR_NOSUCHFIELD,
-206 => DB_ERROR_NOSUCHFIELD,
-208 => DB_ERROR_INVALID,
-219 => DB_ERROR_NOSUCHTABLE,
-297 => DB_ERROR_CONSTRAINT,
-530 => DB_ERROR_CONSTRAINT,
-803 => DB_ERROR_CONSTRAINT,
-551 => DB_ERROR_ACCESS_VIOLATION,
-552 => DB_ERROR_ACCESS_VIOLATION,
-922 => DB_ERROR_NOSUCHDB,
-923 => DB_ERROR_CONNECT_FAILED,
-924 => DB_ERROR_CONNECT_FAILED
);
return $MAP;
}
function adodb_error_ifx()
{
static $MAP = array(
'-201' => DB_ERROR_SYNTAX,
'-206' => DB_ERROR_NOSUCHTABLE,
'-217' => DB_ERROR_NOSUCHFIELD,
'-329' => DB_ERROR_NODBSELECTED,
'-1204' => DB_ERROR_INVALID_DATE,
'-1205' => DB_ERROR_INVALID_DATE,
'-1206' => DB_ERROR_INVALID_DATE,
'-1209' => DB_ERROR_INVALID_DATE,
'-1210' => DB_ERROR_INVALID_DATE,
'-1212' => DB_ERROR_INVALID_DATE
);
return $MAP;
}
function adodb_error_oci8()
{
static $MAP = array(
900 => DB_ERROR_SYNTAX,
904 => DB_ERROR_NOSUCHFIELD,
923 => DB_ERROR_SYNTAX,
942 => DB_ERROR_NOSUCHTABLE,
955 => DB_ERROR_ALREADY_EXISTS,
1476 => DB_ERROR_DIVZERO,
1722 => DB_ERROR_INVALID_NUMBER,
2289 => DB_ERROR_NOSUCHTABLE,
2291 => DB_ERROR_CONSTRAINT,
2449 => DB_ERROR_CONSTRAINT,
);
return $MAP;
}
function adodb_error_mssql()
{
static $MAP = array(
208 => DB_ERROR_NOSUCHTABLE,
2601 => DB_ERROR_ALREADY_EXISTS
);
return $MAP;
}
function adodb_error_mysql()
{
static $MAP = array(
1004 => DB_ERROR_CANNOT_CREATE,
1005 => DB_ERROR_CANNOT_CREATE,
1006 => DB_ERROR_CANNOT_CREATE,
1007 => DB_ERROR_ALREADY_EXISTS,
1008 => DB_ERROR_CANNOT_DROP,
1046 => DB_ERROR_NODBSELECTED,
1050 => DB_ERROR_ALREADY_EXISTS,
1051 => DB_ERROR_NOSUCHTABLE,
1054 => DB_ERROR_NOSUCHFIELD,
1062 => DB_ERROR_ALREADY_EXISTS,
1064 => DB_ERROR_SYNTAX,
1100 => DB_ERROR_NOT_LOCKED,
1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
1146 => DB_ERROR_NOSUCHTABLE,
1048 => DB_ERROR_CONSTRAINT,
);
return $MAP;
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* The following code is adapted from the PEAR DB error handling code.
* Portions (c)1997-2002 The PHP Group.
*/
if (!defined("DB_ERROR")) define("DB_ERROR",-1);
if (!defined("DB_ERROR_SYNTAX")) {
define("DB_ERROR_SYNTAX", -2);
define("DB_ERROR_CONSTRAINT", -3);
define("DB_ERROR_NOT_FOUND", -4);
define("DB_ERROR_ALREADY_EXISTS", -5);
define("DB_ERROR_UNSUPPORTED", -6);
define("DB_ERROR_MISMATCH", -7);
define("DB_ERROR_INVALID", -8);
define("DB_ERROR_NOT_CAPABLE", -9);
define("DB_ERROR_TRUNCATED", -10);
define("DB_ERROR_INVALID_NUMBER", -11);
define("DB_ERROR_INVALID_DATE", -12);
define("DB_ERROR_DIVZERO", -13);
define("DB_ERROR_NODBSELECTED", -14);
define("DB_ERROR_CANNOT_CREATE", -15);
define("DB_ERROR_CANNOT_DELETE", -16);
define("DB_ERROR_CANNOT_DROP", -17);
define("DB_ERROR_NOSUCHTABLE", -18);
define("DB_ERROR_NOSUCHFIELD", -19);
define("DB_ERROR_NEED_MORE_DATA", -20);
define("DB_ERROR_NOT_LOCKED", -21);
define("DB_ERROR_VALUE_COUNT_ON_ROW", -22);
define("DB_ERROR_INVALID_DSN", -23);
define("DB_ERROR_CONNECT_FAILED", -24);
define("DB_ERROR_EXTENSION_NOT_FOUND",-25);
define("DB_ERROR_NOSUCHDB", -25);
define("DB_ERROR_ACCESS_VIOLATION", -26);
}
function adodb_errormsg($value)
{
global $ADODB_LANG,$ADODB_LANG_ARRAY;
if (empty($ADODB_LANG)) $ADODB_LANG = 'en';
if (isset($ADODB_LANG_ARRAY['LANG']) && $ADODB_LANG_ARRAY['LANG'] == $ADODB_LANG) ;
else {
include_once(ADODB_DIR."/lang/adodb-$ADODB_LANG.inc.php");
}
return isset($ADODB_LANG_ARRAY[$value]) ? $ADODB_LANG_ARRAY[$value] : $ADODB_LANG_ARRAY[DB_ERROR];
}
function adodb_error($provider,$dbType,$errno)
{
var_dump($errno);
if (is_numeric($errno) && $errno == 0) return 0;
switch($provider) {
case 'mysql': $map = adodb_error_mysql(); break;
case 'oracle':
case 'oci8': $map = adodb_error_oci8(); break;
case 'ibase': $map = adodb_error_ibase(); break;
case 'odbc': $map = adodb_error_odbc(); break;
case 'mssql':
case 'sybase': $map = adodb_error_mssql(); break;
case 'informix': $map = adodb_error_ifx(); break;
case 'postgres': return adodb_error_pg($errno); break;
default:
return DB_ERROR;
}
print_r($map);
var_dump($errno);
if (isset($map[$errno])) return $map[$errno];
return DB_ERROR;
}
/* ************************************************************************************** */
function adodb_error_pg($errormsg)
{
static $error_regexps = array(
'/(Table does not exist\.|Relation [\"\'].*[\"\'] does not exist|sequence does not exist|class ".+" not found)$/' => DB_ERROR_NOSUCHTABLE,
'/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS,
'/divide by zero$/' => DB_ERROR_DIVZERO,
'/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER,
'/ttribute [\"\'].*[\"\'] not found$|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD,
'/parser: parse error at or near \"/' => DB_ERROR_SYNTAX,
'/referential integrity violation/' => DB_ERROR_CONSTRAINT
);
foreach ($error_regexps as $regexp => $code) {
if (preg_match($regexp, $errormsg)) {
return $code;
}
}
/* Fall back to DB_ERROR if there was no mapping. */
return DB_ERROR;
}
function adodb_error_odbc()
{
static $MAP = array(
'01004' => DB_ERROR_TRUNCATED,
'07001' => DB_ERROR_MISMATCH,
'21S01' => DB_ERROR_MISMATCH,
'21S02' => DB_ERROR_MISMATCH,
'22003' => DB_ERROR_INVALID_NUMBER,
'22008' => DB_ERROR_INVALID_DATE,
'22012' => DB_ERROR_DIVZERO,
'23000' => DB_ERROR_CONSTRAINT,
'24000' => DB_ERROR_INVALID,
'34000' => DB_ERROR_INVALID,
'37000' => DB_ERROR_SYNTAX,
'42000' => DB_ERROR_SYNTAX,
'IM001' => DB_ERROR_UNSUPPORTED,
'S0000' => DB_ERROR_NOSUCHTABLE,
'S0001' => DB_ERROR_NOT_FOUND,
'S0002' => DB_ERROR_NOSUCHTABLE,
'S0011' => DB_ERROR_ALREADY_EXISTS,
'S0012' => DB_ERROR_NOT_FOUND,
'S0021' => DB_ERROR_ALREADY_EXISTS,
'S0022' => DB_ERROR_NOT_FOUND,
'S1000' => DB_ERROR_NOSUCHTABLE,
'S1009' => DB_ERROR_INVALID,
'S1090' => DB_ERROR_INVALID,
'S1C00' => DB_ERROR_NOT_CAPABLE
);
return $MAP;
}
function adodb_error_ibase()
{
static $MAP = array(
-104 => DB_ERROR_SYNTAX,
-150 => DB_ERROR_ACCESS_VIOLATION,
-151 => DB_ERROR_ACCESS_VIOLATION,
-155 => DB_ERROR_NOSUCHTABLE,
-157 => DB_ERROR_NOSUCHFIELD,
-158 => DB_ERROR_VALUE_COUNT_ON_ROW,
-170 => DB_ERROR_MISMATCH,
-171 => DB_ERROR_MISMATCH,
-172 => DB_ERROR_INVALID,
-204 => DB_ERROR_INVALID,
-205 => DB_ERROR_NOSUCHFIELD,
-206 => DB_ERROR_NOSUCHFIELD,
-208 => DB_ERROR_INVALID,
-219 => DB_ERROR_NOSUCHTABLE,
-297 => DB_ERROR_CONSTRAINT,
-530 => DB_ERROR_CONSTRAINT,
-803 => DB_ERROR_CONSTRAINT,
-551 => DB_ERROR_ACCESS_VIOLATION,
-552 => DB_ERROR_ACCESS_VIOLATION,
-922 => DB_ERROR_NOSUCHDB,
-923 => DB_ERROR_CONNECT_FAILED,
-924 => DB_ERROR_CONNECT_FAILED
);
return $MAP;
}
function adodb_error_ifx()
{
static $MAP = array(
'-201' => DB_ERROR_SYNTAX,
'-206' => DB_ERROR_NOSUCHTABLE,
'-217' => DB_ERROR_NOSUCHFIELD,
'-329' => DB_ERROR_NODBSELECTED,
'-1204' => DB_ERROR_INVALID_DATE,
'-1205' => DB_ERROR_INVALID_DATE,
'-1206' => DB_ERROR_INVALID_DATE,
'-1209' => DB_ERROR_INVALID_DATE,
'-1210' => DB_ERROR_INVALID_DATE,
'-1212' => DB_ERROR_INVALID_DATE
);
return $MAP;
}
function adodb_error_oci8()
{
static $MAP = array(
900 => DB_ERROR_SYNTAX,
904 => DB_ERROR_NOSUCHFIELD,
923 => DB_ERROR_SYNTAX,
942 => DB_ERROR_NOSUCHTABLE,
955 => DB_ERROR_ALREADY_EXISTS,
1476 => DB_ERROR_DIVZERO,
1722 => DB_ERROR_INVALID_NUMBER,
2289 => DB_ERROR_NOSUCHTABLE,
2291 => DB_ERROR_CONSTRAINT,
2449 => DB_ERROR_CONSTRAINT,
);
return $MAP;
}
function adodb_error_mssql()
{
static $MAP = array(
208 => DB_ERROR_NOSUCHTABLE,
2601 => DB_ERROR_ALREADY_EXISTS
);
return $MAP;
}
function adodb_error_mysql()
{
static $MAP = array(
1004 => DB_ERROR_CANNOT_CREATE,
1005 => DB_ERROR_CANNOT_CREATE,
1006 => DB_ERROR_CANNOT_CREATE,
1007 => DB_ERROR_ALREADY_EXISTS,
1008 => DB_ERROR_CANNOT_DROP,
1046 => DB_ERROR_NODBSELECTED,
1050 => DB_ERROR_ALREADY_EXISTS,
1051 => DB_ERROR_NOSUCHTABLE,
1054 => DB_ERROR_NOSUCHFIELD,
1062 => DB_ERROR_ALREADY_EXISTS,
1064 => DB_ERROR_SYNTAX,
1100 => DB_ERROR_NOT_LOCKED,
1136 => DB_ERROR_VALUE_COUNT_ON_ROW,
1146 => DB_ERROR_NOSUCHTABLE,
1048 => DB_ERROR_CONSTRAINT,
);
return $MAP;
}
?>
+77 -77
View File
@@ -1,77 +1,77 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
*/
// added Claudio Bustos clbustos#entelchile.net
if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
/**
* Default Error Handler. This will be called with the following params
*
* @param $dbms the RDBMS you are connecting to
* @param $fn the name of the calling function (in uppercase)
* @param $errno the native error number from the database
* @param $errmsg the native error msg from the database
* @param $p1 $fn specific parameter - see below
* @param $P2 $fn specific parameter - see below
*/
function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
{
if (error_reporting() == 0) return; // obey @ protocol
switch($fn) {
case 'EXECUTE':
$sql = $p1;
$inputparams = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
break;
case 'PCONNECT':
case 'CONNECT':
$host = $p1;
$database = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
break;
default:
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
break;
}
/*
* Log connection error somewhere
* 0 message is sent to PHP's system logger, using the Operating System's system
* logging mechanism or a file, depending on what the error_log configuration
* directive is set to.
* 1 message is sent by email to the address in the destination parameter.
* This is the only message type where the fourth parameter, extra_headers is used.
* This message type uses the same internal function as mail() does.
* 2 message is sent through the PHP debugging connection.
* This option is only available if remote debugging has been enabled.
* In this case, the destination parameter specifies the host name or IP address
* and optionally, port number, of the socket receiving the debug information.
* 3 message is appended to the file destination
*/
if (defined('ADODB_ERROR_LOG_TYPE')) {
$t = date('Y-m-d H:i:s');
if (defined('ADODB_ERROR_LOG_DEST'))
error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
else
error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
}
//print "<p>$s</p>";
trigger_error($s,ADODB_ERROR_HANDLER_TYPE);
}
?>
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
*/
/* added Claudio Bustos clbustos#entelchile.net */
if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
/**
* Default Error Handler. This will be called with the following params
*
* @param $dbms the RDBMS you are connecting to
* @param $fn the name of the calling function (in uppercase)
* @param $errno the native error number from the database
* @param $errmsg the native error msg from the database
* @param $p1 $fn specific parameter - see below
* @param $P2 $fn specific parameter - see below
*/
function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
{
if (error_reporting() == 0) return; /* obey @ protocol */
switch($fn) {
case 'EXECUTE':
$sql = $p1;
$inputparams = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
break;
case 'PCONNECT':
case 'CONNECT':
$host = $p1;
$database = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
break;
default:
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
break;
}
/*
* Log connection error somewhere
* 0 message is sent to PHP's system logger, using the Operating System's system
* logging mechanism or a file, depending on what the error_log configuration
* directive is set to.
* 1 message is sent by email to the address in the destination parameter.
* This is the only message type where the fourth parameter, extra_headers is used.
* This message type uses the same internal function as mail() does.
* 2 message is sent through the PHP debugging connection.
* This option is only available if remote debugging has been enabled.
* In this case, the destination parameter specifies the host name or IP address
* and optionally, port number, of the socket receiving the debug information.
* 3 message is appended to the file destination
*/
if (defined('ADODB_ERROR_LOG_TYPE')) {
$t = date('Y-m-d H:i:s');
if (defined('ADODB_ERROR_LOG_DEST'))
error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
else
error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
}
/* print "<p>$s</p>"; */
trigger_error($s,ADODB_ERROR_HANDLER_TYPE);
}
?>
+87 -87
View File
@@ -1,88 +1,88 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
*/
include_once('PEAR.php');
define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
/*
* Enabled the following if you want to terminate scripts when an error occurs
*/
//PEAR::setErrorHandling (PEAR_ERROR_DIE);
/*
* Name of the PEAR_Error derived class to call.
*/
if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');
/*
* Store the last PEAR_Error object here
*/
global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
/**
* Error Handler with PEAR support. This will be called with the following params
*
* @param $dbms the RDBMS you are connecting to
* @param $fn the name of the calling function (in uppercase)
* @param $errno the native error number from the database
* @param $errmsg the native error msg from the database
* @param $p1 $fn specific parameter - see below
* @param $P2 $fn specific parameter - see below
*/
function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
{
global $ADODB_Last_PEAR_Error;
if (error_reporting() == 0) return; // obey @ protocol
switch($fn) {
case 'EXECUTE':
$sql = $p1;
$inputparams = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
break;
case 'PCONNECT':
case 'CONNECT':
$host = $p1;
$database = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
break;
default:
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
break;
}
$class = ADODB_PEAR_ERROR_CLASS;
$ADODB_Last_PEAR_Error = new $class($s, $errno,
$GLOBALS['_PEAR_default_error_mode'],
$GLOBALS['_PEAR_default_error_options'],
$errmsg);
//print "<p>!$s</p>";
}
/**
* Returns last PEAR_Error object. This error might be for an error that
* occured several sql statements ago.
*/
function &ADODB_PEAR_Error()
{
global $ADODB_Last_PEAR_Error;
return $ADODB_Last_PEAR_Error;
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
*/
include_once('PEAR.php');
define('ADODB_ERROR_HANDLER','ADODB_Error_PEAR');
/*
* Enabled the following if you want to terminate scripts when an error occurs
*/
/* PEAR::setErrorHandling (PEAR_ERROR_DIE); */
/*
* Name of the PEAR_Error derived class to call.
*/
if (!defined('ADODB_PEAR_ERROR_CLASS')) define('ADODB_PEAR_ERROR_CLASS','PEAR_Error');
/*
* Store the last PEAR_Error object here
*/
global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
/**
* Error Handler with PEAR support. This will be called with the following params
*
* @param $dbms the RDBMS you are connecting to
* @param $fn the name of the calling function (in uppercase)
* @param $errno the native error number from the database
* @param $errmsg the native error msg from the database
* @param $p1 $fn specific parameter - see below
* @param $P2 $fn specific parameter - see below
*/
function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
{
global $ADODB_Last_PEAR_Error;
if (error_reporting() == 0) return; /* obey @ protocol */
switch($fn) {
case 'EXECUTE':
$sql = $p1;
$inputparams = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
break;
case 'PCONNECT':
case 'CONNECT':
$host = $p1;
$database = $p2;
$s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
break;
default:
$s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
break;
}
$class = ADODB_PEAR_ERROR_CLASS;
$ADODB_Last_PEAR_Error = new $class($s, $errno,
$GLOBALS['_PEAR_default_error_mode'],
$GLOBALS['_PEAR_default_error_options'],
$errmsg);
/* print "<p>!$s</p>"; */
}
/**
* Returns last PEAR_Error object. This error might be for an error that
* occured several sql statements ago.
*/
function &ADODB_PEAR_Error()
{
global $ADODB_Last_PEAR_Error;
return $ADODB_Last_PEAR_Error;
}
?>
+455 -451
View File
@@ -1,452 +1,456 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Less commonly used functions are placed here to reduce size of adodb.inc.php.
*/
// Force key to upper.
// See also http://www.php.net/manual/en/function.array-change-key-case.php
function _array_change_key_case($an_array)
{
if (is_array($an_array)) {
foreach($an_array as $key => $value)
$new_array[strtoupper($key)] = $value;
return $new_array;
}
return $an_array;
}
// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
$hasvalue = false;
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = " multiple size=$size";
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = " size=$size";
else $attr ='';
$s = "<select name=\"$name\"$attr $selectAttr>";
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue=true;
else $compareFields0 = true;
$value = '';
while(!$zthis->EOF) {
$zval = trim(reset($zthis->fields));
if (sizeof($zthis->fields) > 1) {
if (isset($zthis->fields[1]))
$zval2 = trim($zthis->fields[1]);
else
$zval2 = trim(next($zthis->fields));
}
$selected = ($compareFields0) ? $zval : $zval2;
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($hasvalue)
$value = ' value="'.htmlspecialchars($zval2).'"';
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} // while
return $s ."\n</select>\n";
}
/*
Count the number of records this sql statement will return by using
query rewriting techniques...
Does not work with UNIONs.
*/
function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
{
if (preg_match("/^\s*SELECT\s+DISTINCT/i", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
// ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
// but this is only supported by oracle and postgresql...
if ($zthis->dataProvider == 'oci8') {
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
} else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') {
$info = $zthis->ServerInfo();
if (substr($info['version'],0,3) >= 7.1) { // good till version 999
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
}
}
} else {
// now replace SELECT ... FROM with SELECT COUNT(*) FROM
$rewritesql = preg_replace(
'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
// fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
// with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
}
if (isset($rewritesql) && $rewritesql != $sql) {
if ($secs2cache) {
// we only use half the time of secs2cache because the count can quickly
// become inaccurate if new records are added
$qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
} else {
$qryRecs = $zthis->GetOne($rewritesql,$inputarr);
}
if ($qryRecs !== false) return $qryRecs;
}
// query rewrite failed - so try slower way...
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rstest = &$zthis->Execute($rewritesql);
if ($rstest) {
$qryRecs = $rstest->RecordCount();
if ($qryRecs == -1) {
global $ADODB_EXTENSION;
// some databases will return -1 on MoveLast() - change to MoveNext()
if ($ADODB_EXTENSION) {
while(!$rstest->EOF) {
adodb_movenext($rstest);
}
} else {
while(!$rstest->EOF) {
$rstest->MoveNext();
}
}
$qryRecs = $rstest->_currentRow;
}
$rstest->Close();
if ($qryRecs == -1) return 0;
}
return $qryRecs;
}
/*
Code originally from "Cornel G" <[email protected]>
This code will not work with SQL that has UNION in it
Also if you are using CachePageExecute(), there is a strong possibility that
data will get out of synch. use CachePageExecute() only with tables that
rarely change.
*/
function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
$inputarr=false, $arg3=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
$lastpageno=1;
// If an invalid nrows is supplied,
// we assume a default value of 10 rows per page
if (!isset($nrows) || $nrows <= 0) $nrows = 10;
$qryRecs = false; //count records for no offset
$qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
$lastpageno = (int) ceil($qryRecs / $nrows);
$zthis->_maxRecordCount = $qryRecs;
// If page number <= 1, then we are at the first page
if (!isset($page) || $page <= 1) {
$page = 1;
$atfirstpage = true;
}
// ***** Here we check whether $page is the last page or
// whether we are trying to retrieve
// a page number greater than the last page number.
if ($page >= $lastpageno) {
$page = $lastpageno;
$atlastpage = true;
}
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0)
$rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr, $arg3);
else
$rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
$rsreturn->_maxRecordCount = $qryRecs;
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
$rsreturn->LastPageNo($lastpageno);
}
return $rsreturn;
}
// Iván Oliva version
function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page
$page = 1;
$atfirstpage = true;
}
if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page
// ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
// the last page number.
$pagecounter = $page + 1;
$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);
if ($rstest) {
while ($rstest && $rstest->EOF && $pagecounter>0) {
$atlastpage = true;
$pagecounter--;
$pagecounteroffset = $nrows * ($pagecounter - 1);
$rstest->Close();
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);
}
if ($rstest) $rstest->Close();
}
if ($atlastpage) { // If we are at the last page or beyond it, we are going to retrieve it
$page = $pagecounter;
if ($page == 1) $atfirstpage = true; // We have to do this again in case the last page is the same as the first
//... page, that is, the recordset has only 1 page.
}
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr, $arg3);
else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache);
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
}
return $rsreturn;
}
function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
{
if (!$rs) {
printf(ADODB_BAD_RS,'GetUpdateSQL');
return false;
}
$fieldUpdatedCount = 0;
$arrFields = _array_change_key_case($arrFields);
// Get the table name from the existing query.
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/i", $rs->sql, $tableName);
// Get the full where clause excluding the word "WHERE" from
// the existing query.
preg_match('/\sWHERE\s(.*)/i', $rs->sql, $whereClause);
$discard = false;
// not a good hack, improvements?
if ($whereClause)
preg_match('/\s(LIMIT\s.*)/i', $whereClause[1], $discard);
if ($discard)
$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
// updateSQL will contain the full update query when all
// processing has completed.
$updateSQL = "UPDATE " . $tableName[1] . " SET ";
$hasnumeric = isset($rs->fields[0]);
// Loop through all of the fields in the recordset
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
// Get the field from the recordset
$field = $rs->FetchField($i);
// If the recordset field is one
// of the fields passed in then process.
$upperfname = strtoupper($field->name);
if (isset($arrFields[$upperfname])) {
// If the existing field value in the recordset
// is different from the value passed in then
// go ahead and append the field name and new value to
// the update query.
if ($hasnumeric) $val = $rs->fields[$i];
else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
else $val = '';
if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
// Set the counter for the number of fields that will be updated.
$fieldUpdatedCount++;
// Based on the datatype of the field
// Format the value properly for the database
$mt = $rs->MetaType($field->type);
// "mike" <[email protected]> patch and "Ryan Bailey" <[email protected]>
//PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
// is_null requires php 4.0.4
if (/*is_null($arrFields[$fieldname]) ||*/ $arrFields[$upperfname] === 'null')
$updateSQL .= $field->name . " = null, ";
else
switch($mt) {
case 'null':
case "C":
case "X":
case 'B':
$updateSQL .= $field->name . " = " . $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
break;
case "D":
$updateSQL .= $field->name . " = " . $zthis->DBDate($arrFields[$upperfname]) . ", ";
break;
case "T":
$updateSQL .= $field->name . " = " . $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
break;
default:
$updateSQL .= $field->name . " = " . (float) $arrFields[$upperfname] . ", ";
break;
};
};
};
};
// If there were any modified fields then build the rest of the update query.
if ($fieldUpdatedCount > 0 || $forceUpdate) {
// Strip off the comma and space on the end of the update query.
$updateSQL = substr($updateSQL, 0, -2);
// If the recordset has a where clause then use that same where clause
// for the update.
if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];
return $updateSQL;
} else {
return false;
};
}
function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
{
$values = '';
$fields = '';
$arrFields = _array_change_key_case($arrFields);
if (!$rs) {
printf(ADODB_BAD_RS,'GetInsertSQL');
return false;
}
$fieldInsertedCount = 0;
// Get the table name from the existing query.
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/i", $rs->sql, $tableName);
// Loop through all of the fields in the recordset
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
// Get the field from the recordset
$field = $rs->FetchField($i);
// If the recordset field is one
// of the fields passed in then process.
$upperfname = strtoupper($field->name);
if (isset($arrFields[$upperfname])) {
// Set the counter for the number of fields that will be inserted.
$fieldInsertedCount++;
// Get the name of the fields to insert
$fields .= $field->name . ", ";
$mt = $rs->MetaType($field->type);
// "mike" <[email protected]> patch and "Ryan Bailey" <[email protected]>
//PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field.
if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
// Based on the datatype of the field
// Format the value properly for the database
if (/*is_null($arrFields[$fieldname]) ||*/ $arrFields[$upperfname] === 'null')
$values .= "null, ";
else
switch($mt) {
case "C":
case "X":
case 'B':
$values .= $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
break;
case "D":
$values .= $zthis->DBDate($arrFields[$upperfname]) . ", ";
break;
case "T":
$values .= $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
break;
default:
$values .= (float) $arrFields[$upperfname] . ", ";
break;
};
};
};
// If there were any inserted fields then build the rest of the insert query.
if ($fieldInsertedCount > 0) {
// Strip off the comma and space on the end of both the fields
// and their values.
$fields = substr($fields, 0, -2);
$values = substr($values, 0, -2);
// Append the fields and their values to the insert query.
$insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";
return $insertSQL;
} else {
return false;
};
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Less commonly used functions are placed here to reduce size of adodb.inc.php.
*/
/* Force key to upper. */
/* See also http://www.php.net/manual/en/function.array-change-key-case.php */
function _array_change_key_case($an_array)
{
if (is_array($an_array)) {
foreach($an_array as $key => $value)
$new_array[strtoupper($key)] = $value;
return $new_array;
}
return $an_array;
}
/* Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM */
function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
$size=0, $selectAttr='',$compareFields0=true)
{
$hasvalue = false;
if ($multiple or is_array($defstr)) {
if ($size==0) $size=5;
$attr = " multiple size=$size";
if (!strpos($name,'[]')) $name .= '[]';
} else if ($size) $attr = " size=$size";
else $attr ='';
$s = "<select name=\"$name\"$attr $selectAttr>";
if ($blank1stItem)
if (is_string($blank1stItem)) {
$barr = explode(':',$blank1stItem);
if (sizeof($barr) == 1) $barr[] = '';
$s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
} else $s .= "\n<option></option>";
if ($zthis->FieldCount() > 1) $hasvalue=true;
else $compareFields0 = true;
$value = '';
while(!$zthis->EOF) {
$zval = trim(reset($zthis->fields));
if (sizeof($zthis->fields) > 1) {
if (isset($zthis->fields[1]))
$zval2 = trim($zthis->fields[1]);
else
$zval2 = trim(next($zthis->fields));
}
$selected = ($compareFields0) ? $zval : $zval2;
if ($blank1stItem && $zval=="") {
$zthis->MoveNext();
continue;
}
if ($hasvalue)
$value = ' value="'.htmlspecialchars($zval2).'"';
if (is_array($defstr)) {
if (in_array($selected,$defstr))
$s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
else {
if (strcasecmp($selected,$defstr)==0)
$s .= "<option selected$value>".htmlspecialchars($zval).'</option>';
else
$s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
}
$zthis->MoveNext();
} /* while */
return $s ."\n</select>\n";
}
/*
Count the number of records this sql statement will return by using
query rewriting techniques...
Does not work with UNIONs.
*/
function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
{
if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
/* ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias */
/* but this is only supported by oracle and postgresql... */
if ($zthis->dataProvider == 'oci8') {
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql)";
} else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7') {
$info = $zthis->ServerInfo();
if (substr($info['version'],0,3) >= 7.1) { /* good till version 999 */
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
}
}
} else {
/* now replace SELECT ... FROM with SELECT COUNT(*) FROM */
$rewritesql = preg_replace(
'/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
/* fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails */
/* with mssql, access and postgresql. Also a good speedup optimization - skips sorting! */
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql);
}
if (isset($rewritesql) && $rewritesql != $sql) {
if ($secs2cache) {
/* we only use half the time of secs2cache because the count can quickly */
/* become inaccurate if new records are added */
$qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
} else {
$qryRecs = $zthis->GetOne($rewritesql,$inputarr);
}
if ($qryRecs !== false) return $qryRecs;
}
/* query rewrite failed - so try slower way... */
$rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
$rstest = &$zthis->Execute($rewritesql);
if ($rstest) {
$qryRecs = $rstest->RecordCount();
if ($qryRecs == -1) {
global $ADODB_EXTENSION;
/* some databases will return -1 on MoveLast() - change to MoveNext() */
if ($ADODB_EXTENSION) {
while(!$rstest->EOF) {
adodb_movenext($rstest);
}
} else {
while(!$rstest->EOF) {
$rstest->MoveNext();
}
}
$qryRecs = $rstest->_currentRow;
}
$rstest->Close();
if ($qryRecs == -1) return 0;
}
return $qryRecs;
}
/*
Code originally from "Cornel G" <[email protected]>
This code will not work with SQL that has UNION in it
Also if you are using CachePageExecute(), there is a strong possibility that
data will get out of synch. use CachePageExecute() only with tables that
rarely change.
*/
function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
$inputarr=false, $arg3=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
$lastpageno=1;
/* If an invalid nrows is supplied, */
/* we assume a default value of 10 rows per page */
if (!isset($nrows) || $nrows <= 0) $nrows = 10;
$qryRecs = false; /* count records for no offset */
$qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
$lastpageno = (int) ceil($qryRecs / $nrows);
$zthis->_maxRecordCount = $qryRecs;
/* If page number <= 1, then we are at the first page */
if (!isset($page) || $page <= 1) {
$page = 1;
$atfirstpage = true;
}
/* ***** Here we check whether $page is the last page or */
/* whether we are trying to retrieve */
/* a page number greater than the last page number. */
if ($page >= $lastpageno) {
$page = $lastpageno;
$atlastpage = true;
}
/* We get the data we want */
$offset = $nrows * ($page-1);
if ($secs2cache > 0)
$rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr, $arg3);
else
$rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache);
/* Before returning the RecordSet, we set the pagination properties we need */
if ($rsreturn) {
$rsreturn->_maxRecordCount = $qryRecs;
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
$rsreturn->LastPageNo($lastpageno);
}
return $rsreturn;
}
/* Iván Oliva version */
function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $arg3=false, $secs2cache=0)
{
$atfirstpage = false;
$atlastpage = false;
if (!isset($page) || $page <= 1) { /* If page number <= 1, then we are at the first page */
$page = 1;
$atfirstpage = true;
}
if ($nrows <= 0) $nrows = 10; /* If an invalid nrows is supplied, we assume a default value of 10 rows per page */
/* ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than */
/* the last page number. */
$pagecounter = $page + 1;
$pagecounteroffset = ($pagecounter * $nrows) - $nrows;
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);
if ($rstest) {
while ($rstest && $rstest->EOF && $pagecounter>0) {
$atlastpage = true;
$pagecounter--;
$pagecounteroffset = $nrows * ($pagecounter - 1);
$rstest->Close();
if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr, $arg3);
else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $arg3, $secs2cache);
}
if ($rstest) $rstest->Close();
}
if ($atlastpage) { /* If we are at the last page or beyond it, we are going to retrieve it */
$page = $pagecounter;
if ($page == 1) $atfirstpage = true; /* We have to do this again in case the last page is the same as the first */
/* ... page, that is, the recordset has only 1 page. */
}
/* We get the data we want */
$offset = $nrows * ($page-1);
if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr, $arg3);
else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $arg3, $secs2cache);
/* Before returning the RecordSet, we set the pagination properties we need */
if ($rsreturn) {
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
}
return $rsreturn;
}
function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false)
{
if (!$rs) {
printf(ADODB_BAD_RS,'GetUpdateSQL');
return false;
}
$fieldUpdatedCount = 0;
$arrFields = _array_change_key_case($arrFields);
/* Get the table name from the existing query. */
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
/* Get the full where clause excluding the word "WHERE" from */
/* the existing query. */
preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
$discard = false;
/* not a good hack, improvements? */
if ($whereClause)
preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard);
if ($discard)
$whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
/* updateSQL will contain the full update query when all */
/* processing has completed. */
$updateSQL = "UPDATE " . $tableName[1] . " SET ";
$hasnumeric = isset($rs->fields[0]);
/* Loop through all of the fields in the recordset */
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
/* Get the field from the recordset */
$field = $rs->FetchField($i);
/* If the recordset field is one */
/* of the fields passed in then process. */
$upperfname = strtoupper($field->name);
if (isset($arrFields[$upperfname])) {
/* If the existing field value in the recordset */
/* is different from the value passed in then */
/* go ahead and append the field name and new value to */
/* the update query. */
if ($hasnumeric) $val = $rs->fields[$i];
else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
else $val = '';
if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
/* Set the counter for the number of fields that will be updated. */
$fieldUpdatedCount++;
/* Based on the datatype of the field */
/* Format the value properly for the database */
$mt = $rs->MetaType($field->type);
/* "mike" <[email protected]> patch and "Ryan Bailey" <[email protected]> */
/* PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field. */
if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
/* is_null requires php 4.0.4 */
if (/*is_null($arrFields[$fieldname]) ||*/ $arrFields[$upperfname] === 'null')
$updateSQL .= $field->name . " = null, ";
else
switch($mt) {
case 'null':
case "C":
case "X":
case 'B':
$updateSQL .= $field->name . " = " . $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
break;
case "D":
$updateSQL .= $field->name . " = " . $zthis->DBDate($arrFields[$upperfname]) . ", ";
break;
case "T":
$updateSQL .= $field->name . " = " . $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
break;
default:
$val = $arrFields[$upperfname];
if (!is_numeric($val)) $val = (float) $val;
$updateSQL .= $field->name . " = " . $val . ", ";
break;
};
};
};
};
/* If there were any modified fields then build the rest of the update query. */
if ($fieldUpdatedCount > 0 || $forceUpdate) {
/* Strip off the comma and space on the end of the update query. */
$updateSQL = substr($updateSQL, 0, -2);
/* If the recordset has a where clause then use that same where clause */
/* for the update. */
if ($whereClause[1]) $updateSQL .= " WHERE " . $whereClause[1];
return $updateSQL;
} else {
return false;
};
}
function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false)
{
$values = '';
$fields = '';
$arrFields = _array_change_key_case($arrFields);
if (!$rs) {
printf(ADODB_BAD_RS,'GetInsertSQL');
return false;
}
$fieldInsertedCount = 0;
/* Get the table name from the existing query. */
preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
/* Loop through all of the fields in the recordset */
for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
/* Get the field from the recordset */
$field = $rs->FetchField($i);
/* If the recordset field is one */
/* of the fields passed in then process. */
$upperfname = strtoupper($field->name);
if (isset($arrFields[$upperfname])) {
/* Set the counter for the number of fields that will be inserted. */
$fieldInsertedCount++;
/* Get the name of the fields to insert */
$fields .= $field->name . ", ";
$mt = $rs->MetaType($field->type);
/* "mike" <[email protected]> patch and "Ryan Bailey" <[email protected]> */
/* PostgreSQL uses a 't' or 'f' and therefore needs to be processed as a string ('C') type field. */
if ((strncmp($zthis->databaseType,"postgres",8) === 0) && ($mt == "L")) $mt = "C";
/* Based on the datatype of the field */
/* Format the value properly for the database */
if (/*is_null($arrFields[$fieldname]) ||*/ $arrFields[$upperfname] === 'null')
$values .= "null, ";
else
switch($mt) {
case "C":
case "X":
case 'B':
$values .= $zthis->qstr($arrFields[$upperfname],$magicq) . ", ";
break;
case "D":
$values .= $zthis->DBDate($arrFields[$upperfname]) . ", ";
break;
case "T":
$values .= $zthis->DBTimeStamp($arrFields[$upperfname]) . ", ";
break;
default:
$val = $arrFields[$upperfname];
if (!is_numeric($val)) $val = (float) $val;
$values .= $val . ", ";
break;
};
};
};
/* If there were any inserted fields then build the rest of the insert query. */
if ($fieldInsertedCount > 0) {
/* Strip off the comma and space on the end of both the fields */
/* and their values. */
$fields = substr($fields, 0, -2);
$values = substr($values, 0, -2);
/* Append the fields and their values to the insert query. */
$insertSQL = "INSERT INTO " . $tableName[1] . " ( $fields ) VALUES ( $values )";
return $insertSQL;
} else {
return false;
};
}
?>
+289 -289
View File
@@ -1,289 +1,289 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
This class provides recordset pagination with
First/Prev/Next/Last links.
Feel free to modify this class for your own use as
it is very basic. To learn how to use it, see the
example in adodb/tests/testpaging.php.
"Pablo Costa" <[email protected]> implemented Render_PageLinks().
Please note, this class is entirely unsupported,
and no free support requests except for bug reports
will be entertained by the author.
My company also sells a commercial pagination
object at http://phplens.com/ with much more
functionality, including search, create, edit,
delete records.
*/
class ADODB_Pager {
var $id; // unique id for pager (defaults to 'adodb')
var $db; // ADODB connection object
var $sql; // sql used
var $rs; // recordset generated
var $curr_page; // current page number before Render() called, calculated in constructor
var $rows; // number of rows per page
var $linksPerPage=10; // number of links per page in navigation bar
var $showPageLinks;
var $gridAttributes = 'width=100% border=1 bgcolor=white';
// Localize text strings here
var $first = '<code>|&lt;</code>';
var $prev = '<code>&lt;&lt;</code>';
var $next = '<code>>></code>';
var $last = '<code>>|</code>';
var $moreLinks = '...';
var $startLinks = '...';
var $gridHeader = false;
var $htmlSpecialChars = true;
var $page = 'Page';
var $linkSelectedColor = 'red';
var $cache = 0; #secs to cache with CachePageExecute()
//----------------------------------------------
// constructor
//
// $db adodb connection object
// $sql sql statement
// $id optional id to identify which pager,
// if you have multiple on 1 page.
// $id should be only be [a-z0-9]*
//
function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
{
global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
$curr_page = $id.'_curr_page';
if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
$this->sql = $sql;
$this->id = $id;
$this->db = $db;
$this->showPageLinks = $showPageLinks;
$next_page = $id.'_next_page';
if (isset($HTTP_GET_VARS[$next_page])) {
$HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
}
if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
$this->curr_page = $HTTP_SESSION_VARS[$curr_page];
}
//---------------------------
// Display link to first page
function Render_First($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp;
<?php
} else {
print "$this->first &nbsp; ";
}
}
//--------------------------
// Display link to next page
function render_next($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp;
<?php
} else {
print "$this->next &nbsp; ";
}
}
//------------------
// Link to last page
//
// for better performance with large recordsets, you can set
// $this->db->pageExecuteCountRows = false, which disables
// last page counting.
function render_last($anchor=true)
{
global $PHP_SELF;
if (!$this->db->pageExecuteCountRows) return;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp;
<?php
} else {
print "$this->last &nbsp; ";
}
}
//---------------------------------------------------
// original code by "Pablo Costa" <[email protected]>
function render_pagelinks()
{
global $PHP_SELF;
$pages = $this->rs->LastPageNo();
$linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;
for($i=1; $i <= $pages; $i+=$linksperpage)
{
if($this->rs->AbsolutePage() >= $i)
{
$start = $i;
}
}
$numbers = '';
$end = $start+$linksperpage-1;
$link = $this->id . "_next_page";
if($end > $pages) $end = $pages;
if ($this->startLinks && $start > 1) {
$pos = $start - 1;
$numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a> ";
}
for($i=$start; $i <= $end; $i++) {
if ($this->rs->AbsolutePage() == $i)
$numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font> ";
else
$numbers .= "<a href=$PHP_SELF?$link=$i>$i</a> ";
}
if ($this->moreLinks && $end < $pages)
$numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a> ";
print $numbers . ' &nbsp; ';
}
// Link to previous page
function render_prev($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp;
<?php
} else {
print "$this->prev &nbsp; ";
}
}
//--------------------------------------------------------
// Simply rendering of grid. You should override this for
// better control over the format of the grid
//
// We use output buffering to keep code clean and readable.
function RenderGrid()
{
global $gSQLBlockRows; // used by rs2html to indicate how many rows to display
include_once(ADODB_DIR.'/tohtml.inc.php');
ob_start();
$gSQLBlockRows = $this->rows;
rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);
$s = ob_get_contents();
ob_end_clean();
return $s;
}
//-------------------------------------------------------
// Navigation bar
//
// we use output buffering to keep the code easy to read.
function RenderNav()
{
ob_start();
if (!$this->rs->AtFirstPage()) {
$this->Render_First();
$this->Render_Prev();
} else {
$this->Render_First(false);
$this->Render_Prev(false);
}
if ($this->showPageLinks){
$this->Render_PageLinks();
}
if (!$this->rs->AtLastPage()) {
$this->Render_Next();
$this->Render_Last();
} else {
$this->Render_Next(false);
$this->Render_Last(false);
}
$s = ob_get_contents();
ob_end_clean();
return $s;
}
//-------------------
// This is the footer
function RenderPageCount()
{
if (!$this->db->pageExecuteCountRows) return '';
$lastPage = $this->rs->LastPageNo();
if ($lastPage == -1) $lastPage = 1; // check for empty rs.
return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";
}
//-----------------------------------
// Call this class to draw everything.
function Render($rows=10)
{
global $ADODB_COUNTRECS;
$this->rows = $rows;
$savec = $ADODB_COUNTRECS;
if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
if ($this->cache)
$rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
else
$rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
$ADODB_COUNTRECS = $savec;
$this->rs = &$rs;
if (!$rs) {
print "<h3>Query failed: $this->sql</h3>";
return;
}
if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage()))
$header = $this->RenderNav();
else
$header = "&nbsp;";
$grid = $this->RenderGrid();
$footer = $this->RenderPageCount();
$rs->Close();
$this->rs = false;
$this->RenderLayout($header,$grid,$footer);
}
//------------------------------------------------------
// override this to control overall layout and formating
function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')
{
echo "<table ".$attributes."><tr><td>",
$header,
"</td></tr><tr><td>",
$grid,
"</td></tr><tr><td>",
$footer,
"</td></tr></table>";
}
}
?>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
This class provides recordset pagination with
First/Prev/Next/Last links.
Feel free to modify this class for your own use as
it is very basic. To learn how to use it, see the
example in adodb/tests/testpaging.php.
"Pablo Costa" <[email protected]> implemented Render_PageLinks().
Please note, this class is entirely unsupported,
and no free support requests except for bug reports
will be entertained by the author.
My company also sells a commercial pagination
object at http://phplens.com/ with much more
functionality, including search, create, edit,
delete records.
*/
class ADODB_Pager {
var $id; /* unique id for pager (defaults to 'adodb') */
var $db; /* ADODB connection object */
var $sql; /* sql used */
var $rs; /* recordset generated */
var $curr_page; /* current page number before Render() called, calculated in constructor */
var $rows; /* number of rows per page */
var $linksPerPage=10; /* number of links per page in navigation bar */
var $showPageLinks;
var $gridAttributes = 'width=100% border=1 bgcolor=white';
/* Localize text strings here */
var $first = '<code>|&lt;</code>';
var $prev = '<code>&lt;&lt;</code>';
var $next = '<code>>></code>';
var $last = '<code>>|</code>';
var $moreLinks = '...';
var $startLinks = '...';
var $gridHeader = false;
var $htmlSpecialChars = true;
var $page = 'Page';
var $linkSelectedColor = 'red';
var $cache = 0; #secs to cache with CachePageExecute()
/* ---------------------------------------------- */
/* constructor */
/* */
/* $db adodb connection object */
/* $sql sql statement */
/* $id optional id to identify which pager, */
/* if you have multiple on 1 page. */
/* $id should be only be [a-z0-9]* */
/* */
function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
{
global $HTTP_SERVER_VARS,$PHP_SELF,$HTTP_SESSION_VARS,$HTTP_GET_VARS;
$curr_page = $id.'_curr_page';
if (empty($PHP_SELF)) $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF'];
$this->sql = $sql;
$this->id = $id;
$this->db = $db;
$this->showPageLinks = $showPageLinks;
$next_page = $id.'_next_page';
if (isset($HTTP_GET_VARS[$next_page])) {
$HTTP_SESSION_VARS[$curr_page] = $HTTP_GET_VARS[$next_page];
}
if (empty($HTTP_SESSION_VARS[$curr_page])) $HTTP_SESSION_VARS[$curr_page] = 1; ## at first page
$this->curr_page = $HTTP_SESSION_VARS[$curr_page];
}
/* --------------------------- */
/* Display link to first page */
function Render_First($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id;?>_next_page=1"><?php echo $this->first;?></a> &nbsp;
<?php
} else {
print "$this->first &nbsp; ";
}
}
/* -------------------------- */
/* Display link to next page */
function render_next($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() + 1 ?>"><?php echo $this->next;?></a> &nbsp;
<?php
} else {
print "$this->next &nbsp; ";
}
}
/* ------------------ */
/* Link to last page */
/* */
/* for better performance with large recordsets, you can set */
/* $this->db->pageExecuteCountRows = false, which disables */
/* last page counting. */
function render_last($anchor=true)
{
global $PHP_SELF;
if (!$this->db->pageExecuteCountRows) return;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->LastPageNo() ?>"><?php echo $this->last;?></a> &nbsp;
<?php
} else {
print "$this->last &nbsp; ";
}
}
/* --------------------------------------------------- */
/* original code by "Pablo Costa" <[email protected]> */
function render_pagelinks()
{
global $PHP_SELF;
$pages = $this->rs->LastPageNo();
$linksperpage = $this->linksPerPage ? $this->linksPerPage : $pages;
for($i=1; $i <= $pages; $i+=$linksperpage)
{
if($this->rs->AbsolutePage() >= $i)
{
$start = $i;
}
}
$numbers = '';
$end = $start+$linksperpage-1;
$link = $this->id . "_next_page";
if($end > $pages) $end = $pages;
if ($this->startLinks && $start > 1) {
$pos = $start - 1;
$numbers .= "<a href=$PHP_SELF?$link=$pos>$this->startLinks</a> ";
}
for($i=$start; $i <= $end; $i++) {
if ($this->rs->AbsolutePage() == $i)
$numbers .= "<font color=$this->linkSelectedColor><b>$i</b></font> ";
else
$numbers .= "<a href=$PHP_SELF?$link=$i>$i</a> ";
}
if ($this->moreLinks && $end < $pages)
$numbers .= "<a href=$PHP_SELF?$link=$i>$this->moreLinks</a> ";
print $numbers . ' &nbsp; ';
}
/* Link to previous page */
function render_prev($anchor=true)
{
global $PHP_SELF;
if ($anchor) {
?>
<a href="<?php echo $PHP_SELF,'?',$this->id,'_next_page=',$this->rs->AbsolutePage() - 1 ?>"><?php echo $this->prev;?></a> &nbsp;
<?php
} else {
print "$this->prev &nbsp; ";
}
}
/* -------------------------------------------------------- */
/* Simply rendering of grid. You should override this for */
/* better control over the format of the grid */
/* */
/* We use output buffering to keep code clean and readable. */
function RenderGrid()
{
global $gSQLBlockRows; /* used by rs2html to indicate how many rows to display */
include_once(ADODB_DIR.'/tohtml.inc.php');
ob_start();
$gSQLBlockRows = $this->rows;
rs2html($this->rs,$this->gridAttributes,$this->gridHeader,$this->htmlSpecialChars);
$s = ob_get_contents();
ob_end_clean();
return $s;
}
/* ------------------------------------------------------- */
/* Navigation bar */
/* */
/* we use output buffering to keep the code easy to read. */
function RenderNav()
{
ob_start();
if (!$this->rs->AtFirstPage()) {
$this->Render_First();
$this->Render_Prev();
} else {
$this->Render_First(false);
$this->Render_Prev(false);
}
if ($this->showPageLinks){
$this->Render_PageLinks();
}
if (!$this->rs->AtLastPage()) {
$this->Render_Next();
$this->Render_Last();
} else {
$this->Render_Next(false);
$this->Render_Last(false);
}
$s = ob_get_contents();
ob_end_clean();
return $s;
}
/* ------------------- */
/* This is the footer */
function RenderPageCount()
{
if (!$this->db->pageExecuteCountRows) return '';
$lastPage = $this->rs->LastPageNo();
if ($lastPage == -1) $lastPage = 1; /* check for empty rs. */
return "<font size=-1>$this->page ".$this->curr_page."/".$lastPage."</font>";
}
/* ----------------------------------- */
/* Call this class to draw everything. */
function Render($rows=10)
{
global $ADODB_COUNTRECS;
$this->rows = $rows;
$savec = $ADODB_COUNTRECS;
if ($this->db->pageExecuteCountRows) $ADODB_COUNTRECS = true;
if ($this->cache)
$rs = &$this->db->CachePageExecute($this->cache,$this->sql,$rows,$this->curr_page);
else
$rs = &$this->db->PageExecute($this->sql,$rows,$this->curr_page);
$ADODB_COUNTRECS = $savec;
$this->rs = &$rs;
if (!$rs) {
print "<h3>Query failed: $this->sql</h3>";
return;
}
if (!$rs->EOF && (!$rs->AtFirstPage() || !$rs->AtLastPage()))
$header = $this->RenderNav();
else
$header = "&nbsp;";
$grid = $this->RenderGrid();
$footer = $this->RenderPageCount();
$rs->Close();
$this->rs = false;
$this->RenderLayout($header,$grid,$footer);
}
/* ------------------------------------------------------ */
/* override this to control overall layout and formating */
function RenderLayout($header,$grid,$footer,$attributes='border=1 bgcolor=beige')
{
echo "<table ".$attributes."><tr><td>",
$header,
"</td></tr><tr><td>",
$grid,
"</td></tr><tr><td>",
$footer,
"</td></tr></table>";
}
}
?>
+356 -356
View File
@@ -1,357 +1,357 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* PEAR DB Emulation Layer for ADODB.
*
* The following code is modelled on PEAR DB code by Stig Bakken <[email protected]> |
* and Tomas V.V.Cox <[email protected]>. Portions (c)1997-2002 The PHP Group.
*/
/*
We support:
DB_Common
---------
query - returns PEAR_Error on error
limitQuery - return PEAR_Error on error
prepare - does not return PEAR_Error on error
execute - does not return PEAR_Error on error
setFetchMode - supports ASSOC and ORDERED
errorNative
quote
nextID
disconnect
DB_Result
---------
numRows - returns -1 if not supported
numCols
fetchInto - does not support passing of fetchmode
fetchRows - does not support passing of fetchmode
free
*/
define('ADODB_PEAR',dirname(__FILE__));
require_once "PEAR.php";
require_once ADODB_PEAR."/adodb-errorpear.inc.php";
require_once ADODB_PEAR."/adodb.inc.php";
if (!defined('DB_OK')) {
define("DB_OK", 1);
define("DB_ERROR",-1);
/**
* This is a special constant that tells DB the user hasn't specified
* any particular get mode, so the default should be used.
*/
define('DB_FETCHMODE_DEFAULT', 0);
/**
* Column data indexed by numbers, ordered from 0 and up
*/
define('DB_FETCHMODE_ORDERED', 1);
/**
* Column data indexed by column names
*/
define('DB_FETCHMODE_ASSOC', 2);
/* for compatibility */
define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
/**
* these are constants for the tableInfo-function
* they are bitwised or'ed. so if there are more constants to be defined
* in the future, adjust DB_TABLEINFO_FULL accordingly
*/
define('DB_TABLEINFO_ORDER', 1);
define('DB_TABLEINFO_ORDERTABLE', 2);
define('DB_TABLEINFO_FULL', 3);
}
/**
* The main "DB" class is simply a container class with some static
* methods for creating DB objects as well as some utility functions
* common to all parts of DB.
*
*/
class DB
{
/**
* Create a new DB object for the specified database type
*
* @param $type string database type, for example "mysql"
*
* @return object a newly created DB object, or a DB error code on
* error
*/
function &factory($type)
{
include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");
$obj = &NewADOConnection($type);
if (!is_object($obj)) return new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
return $obj;
}
/**
* Create a new DB object and connect to the specified database
*
* @param $dsn mixed "data source name", see the DB::parseDSN
* method for a description of the dsn format. Can also be
* specified as an array of the format returned by DB::parseDSN.
*
* @param $options mixed if boolean (or scalar), tells whether
* this connection should be persistent (for backends that support
* this). This parameter can also be an array of options, see
* DB_common::setOption for more information on connection
* options.
*
* @return object a newly created DB connection object, or a DB
* error object on error
*
* @see DB::parseDSN
* @see DB::isError
*/
function &connect($dsn, $options = false)
{
if (is_array($dsn)) {
$dsninfo = $dsn;
} else {
$dsninfo = DB::parseDSN($dsn);
}
switch ($dsninfo["phptype"]) {
case 'pgsql': $type = 'postgres7'; break;
case 'ifx': $type = 'informix9'; break;
default: $type = $dsninfo["phptype"]; break;
}
if (is_array($options) && isset($options["debug"]) &&
$options["debug"] >= 2) {
// expose php errors with sufficient debug level
@include_once("adodb-$type.inc.php");
} else {
@include_once("adodb-$type.inc.php");
}
@$obj =&NewADOConnection($type);
if (!is_object($obj)) return new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
if (is_array($options)) {
foreach($options as $k => $v) {
switch(strtolower($k)) {
case 'persistent': $persist = $v; break;
#ibase
case 'dialect': $obj->dialect = $v; break;
case 'charset': $obj->charset = $v; break;
case 'buffers': $obj->buffers = $v; break;
#ado
case 'charpage': $obj->charPage = $v; break;
#mysql
case 'clientflags': $obj->clientFlags = $v; break;
}
}
} else {
$persist = false;
}
if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
else $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
if (!$ok) return ADODB_PEAR_Error();
return $obj;
}
/**
* Return the DB API version
*
* @return int the DB API version number
*/
function apiVersion()
{
return 2;
}
/**
* Tell whether a result code from a DB method is an error
*
* @param $value int result code
*
* @return bool whether $value is an error
*/
function isError($value)
{
return (is_object($value) &&
(get_class($value) == 'db_error' ||
is_subclass_of($value, 'db_error')));
}
/**
* Tell whether a result code from a DB method is a warning.
* Warnings differ from errors in that they are generated by DB,
* and are not fatal.
*
* @param $value mixed result value
*
* @return bool whether $value is a warning
*/
function isWarning($value)
{
return is_object($value) &&
(get_class( $value ) == "db_warning" ||
is_subclass_of($value, "db_warning"));
}
/**
* Parse a data source name
*
* @param $dsn string Data Source Name to be parsed
*
* @return array an associative array with the following keys:
*
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
*
* The format of the supplied DSN is in its fullest form:
*
* phptype(dbsyntax)://username:password@protocol+hostspec/database
*
* Most variations are allowed:
*
* phptype://username:password@protocol+hostspec:110//usr/db_file.db
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
*
* @author Tomas V.V.Cox <[email protected]>
*/
function parseDSN($dsn)
{
if (is_array($dsn)) {
return $dsn;
}
$parsed = array(
'phptype' => false,
'dbsyntax' => false,
'protocol' => false,
'hostspec' => false,
'database' => false,
'username' => false,
'password' => false
);
// Find phptype and dbsyntax
if (($pos = strpos($dsn, '://')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 3);
} else {
$str = $dsn;
$dsn = NULL;
}
// Get phptype and dbsyntax
// $str => phptype(dbsyntax)
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1];
$parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
} else {
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
}
if (empty($dsn)) {
return $parsed;
}
// Get (if found): username and password
// $dsn => username:password@protocol+hostspec/database
if (($at = strpos($dsn,'@')) !== false) {
$str = substr($dsn, 0, $at);
$dsn = substr($dsn, $at + 1);
if (($pos = strpos($str, ':')) !== false) {
$parsed['username'] = urldecode(substr($str, 0, $pos));
$parsed['password'] = urldecode(substr($str, $pos + 1));
} else {
$parsed['username'] = urldecode($str);
}
}
// Find protocol and hostspec
// $dsn => protocol+hostspec/database
if (($pos=strpos($dsn, '/')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 1);
} else {
$str = $dsn;
$dsn = NULL;
}
// Get protocol + hostspec
// $str => protocol+hostspec
if (($pos=strpos($str, '+')) !== false) {
$parsed['protocol'] = substr($str, 0, $pos);
$parsed['hostspec'] = urldecode(substr($str, $pos + 1));
} else {
$parsed['hostspec'] = urldecode($str);
}
// Get dabase if any
// $dsn => database
if (!empty($dsn)) {
$parsed['database'] = $dsn;
}
return $parsed;
}
/**
* Load a PHP database extension if it is not loaded already.
*
* @access public
*
* @param $name the base name of the extension (without the .so or
* .dll suffix)
*
* @return bool true if the extension was already or successfully
* loaded, false if it could not be loaded
*/
function assertExtension($name)
{
if (!extension_loaded($name)) {
$dlext = (substr(PHP_OS, 0, 3) == 'WIN') ? '.dll' : '.so';
@dl($name . $dlext);
}
if (!extension_loaded($name)) {
return false;
}
return true;
}
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* PEAR DB Emulation Layer for ADODB.
*
* The following code is modelled on PEAR DB code by Stig Bakken <[email protected]> |
* and Tomas V.V.Cox <[email protected]>. Portions (c)1997-2002 The PHP Group.
*/
/*
We support:
DB_Common
---------
query - returns PEAR_Error on error
limitQuery - return PEAR_Error on error
prepare - does not return PEAR_Error on error
execute - does not return PEAR_Error on error
setFetchMode - supports ASSOC and ORDERED
errorNative
quote
nextID
disconnect
DB_Result
---------
numRows - returns -1 if not supported
numCols
fetchInto - does not support passing of fetchmode
fetchRows - does not support passing of fetchmode
free
*/
define('ADODB_PEAR',dirname(__FILE__));
require_once "PEAR.php";
require_once ADODB_PEAR."/adodb-errorpear.inc.php";
require_once ADODB_PEAR."/adodb.inc.php";
if (!defined('DB_OK')) {
define("DB_OK", 1);
define("DB_ERROR",-1);
/**
* This is a special constant that tells DB the user hasn't specified
* any particular get mode, so the default should be used.
*/
define('DB_FETCHMODE_DEFAULT', 0);
/**
* Column data indexed by numbers, ordered from 0 and up
*/
define('DB_FETCHMODE_ORDERED', 1);
/**
* Column data indexed by column names
*/
define('DB_FETCHMODE_ASSOC', 2);
/* for compatibility */
define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED);
define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC);
/**
* these are constants for the tableInfo-function
* they are bitwised or'ed. so if there are more constants to be defined
* in the future, adjust DB_TABLEINFO_FULL accordingly
*/
define('DB_TABLEINFO_ORDER', 1);
define('DB_TABLEINFO_ORDERTABLE', 2);
define('DB_TABLEINFO_FULL', 3);
}
/**
* The main "DB" class is simply a container class with some static
* methods for creating DB objects as well as some utility functions
* common to all parts of DB.
*
*/
class DB
{
/**
* Create a new DB object for the specified database type
*
* @param $type string database type, for example "mysql"
*
* @return object a newly created DB object, or a DB error code on
* error
*/
function &factory($type)
{
include_once(ADODB_DIR."/drivers/adodb-$type.inc.php");
$obj = &NewADOConnection($type);
if (!is_object($obj)) return new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
return $obj;
}
/**
* Create a new DB object and connect to the specified database
*
* @param $dsn mixed "data source name", see the DB::parseDSN
* method for a description of the dsn format. Can also be
* specified as an array of the format returned by DB::parseDSN.
*
* @param $options mixed if boolean (or scalar), tells whether
* this connection should be persistent (for backends that support
* this). This parameter can also be an array of options, see
* DB_common::setOption for more information on connection
* options.
*
* @return object a newly created DB connection object, or a DB
* error object on error
*
* @see DB::parseDSN
* @see DB::isError
*/
function &connect($dsn, $options = false)
{
if (is_array($dsn)) {
$dsninfo = $dsn;
} else {
$dsninfo = DB::parseDSN($dsn);
}
switch ($dsninfo["phptype"]) {
case 'pgsql': $type = 'postgres7'; break;
case 'ifx': $type = 'informix9'; break;
default: $type = $dsninfo["phptype"]; break;
}
if (is_array($options) && isset($options["debug"]) &&
$options["debug"] >= 2) {
/* expose php errors with sufficient debug level */
@include_once("adodb-$type.inc.php");
} else {
@include_once("adodb-$type.inc.php");
}
@$obj =&NewADOConnection($type);
if (!is_object($obj)) return new PEAR_Error('Unknown Database Driver: '.$dsninfo['phptype'],-1);
if (is_array($options)) {
foreach($options as $k => $v) {
switch(strtolower($k)) {
case 'persistent': $persist = $v; break;
#ibase
case 'dialect': $obj->dialect = $v; break;
case 'charset': $obj->charset = $v; break;
case 'buffers': $obj->buffers = $v; break;
#ado
case 'charpage': $obj->charPage = $v; break;
#mysql
case 'clientflags': $obj->clientFlags = $v; break;
}
}
} else {
$persist = false;
}
if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
else $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
if (!$ok) return ADODB_PEAR_Error();
return $obj;
}
/**
* Return the DB API version
*
* @return int the DB API version number
*/
function apiVersion()
{
return 2;
}
/**
* Tell whether a result code from a DB method is an error
*
* @param $value int result code
*
* @return bool whether $value is an error
*/
function isError($value)
{
return (is_object($value) &&
(get_class($value) == 'db_error' ||
is_subclass_of($value, 'db_error')));
}
/**
* Tell whether a result code from a DB method is a warning.
* Warnings differ from errors in that they are generated by DB,
* and are not fatal.
*
* @param $value mixed result value
*
* @return bool whether $value is a warning
*/
function isWarning($value)
{
return is_object($value) &&
(get_class( $value ) == "db_warning" ||
is_subclass_of($value, "db_warning"));
}
/**
* Parse a data source name
*
* @param $dsn string Data Source Name to be parsed
*
* @return array an associative array with the following keys:
*
* phptype: Database backend used in PHP (mysql, odbc etc.)
* dbsyntax: Database used with regards to SQL syntax etc.
* protocol: Communication protocol to use (tcp, unix etc.)
* hostspec: Host specification (hostname[:port])
* database: Database to use on the DBMS server
* username: User name for login
* password: Password for login
*
* The format of the supplied DSN is in its fullest form:
*
* phptype(dbsyntax)://username:password@protocol+hostspec/database
*
* Most variations are allowed:
*
* phptype://username:password@protocol+hostspec:110//usr/db_file.db
* phptype://username:password@hostspec/database_name
* phptype://username:password@hostspec
* phptype://username@hostspec
* phptype://hostspec/database
* phptype://hostspec
* phptype(dbsyntax)
* phptype
*
* @author Tomas V.V.Cox <[email protected]>
*/
function parseDSN($dsn)
{
if (is_array($dsn)) {
return $dsn;
}
$parsed = array(
'phptype' => false,
'dbsyntax' => false,
'protocol' => false,
'hostspec' => false,
'database' => false,
'username' => false,
'password' => false
);
/* Find phptype and dbsyntax */
if (($pos = strpos($dsn, ':/* ')) !== false) { */
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 3);
} else {
$str = $dsn;
$dsn = NULL;
}
/* Get phptype and dbsyntax */
/* $str => phptype(dbsyntax) */
if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) {
$parsed['phptype'] = $arr[1];
$parsed['dbsyntax'] = (empty($arr[2])) ? $arr[1] : $arr[2];
} else {
$parsed['phptype'] = $str;
$parsed['dbsyntax'] = $str;
}
if (empty($dsn)) {
return $parsed;
}
/* Get (if found): username and password */
/* $dsn => username:password@protocol+hostspec/database */
if (($at = strpos($dsn,'@')) !== false) {
$str = substr($dsn, 0, $at);
$dsn = substr($dsn, $at + 1);
if (($pos = strpos($str, ':')) !== false) {
$parsed['username'] = urldecode(substr($str, 0, $pos));
$parsed['password'] = urldecode(substr($str, $pos + 1));
} else {
$parsed['username'] = urldecode($str);
}
}
/* Find protocol and hostspec */
/* $dsn => protocol+hostspec/database */
if (($pos=strpos($dsn, '/')) !== false) {
$str = substr($dsn, 0, $pos);
$dsn = substr($dsn, $pos + 1);
} else {
$str = $dsn;
$dsn = NULL;
}
/* Get protocol + hostspec */
/* $str => protocol+hostspec */
if (($pos=strpos($str, '+')) !== false) {
$parsed['protocol'] = substr($str, 0, $pos);
$parsed['hostspec'] = urldecode(substr($str, $pos + 1));
} else {
$parsed['hostspec'] = urldecode($str);
}
/* Get dabase if any */
/* $dsn => database */
if (!empty($dsn)) {
$parsed['database'] = $dsn;
}
return $parsed;
}
/**
* Load a PHP database extension if it is not loaded already.
*
* @access public
*
* @param $name the base name of the extension (without the .so or
* .dll suffix)
*
* @return bool true if the extension was already or successfully
* loaded, false if it could not be loaded
*/
function assertExtension($name)
{
if (!extension_loaded($name)) {
$dlext = (substr(PHP_OS, 0, 3) == 'WIN') ? '.dll' : '.so';
@dl($name . $dlext);
}
if (!extension_loaded($name)) {
return false;
}
return true;
}
}
?>
File diff suppressed because it is too large Load Diff
+431
View File
@@ -0,0 +1,431 @@
<?php
/*
V3.40 19 May 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version of ADODB is available at http://php.weblogs.com/adodb
======================================================================
This file provides PHP4 session management using the ADODB database
wrapper library, using Oracle CLOB's to store data. Contributed by [email protected].
Example
=======
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
To force non-persistent connections, call adodb_session_open first before session_start():
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
adodb_session_open(false,false,false);
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
Installation
============
1. Create this table in your database (syntax might vary depending on your db):
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
EXPIREREF varchar(64),
DATA CLOB,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
$ADODB_SESSION_USE_LOBS = false; (or, if you wanna use CLOBS (= 'CLOB') or ( = 'BLOB')
3. Recommended is PHP 4.0.6 or later. There are documented
session bugs in earlier versions of PHP.
4. If you want to receive notifications when a session expires, then
you can tag a session with an EXPIREREF, and before the session
record is deleted, we can call a function that will pass the EXPIREREF
as the first parameter, and the session key as the second parameter.
To do this, define a notification function, say NotifyFn:
function NotifyFn($expireref, $sesskey)
{
}
Then define a global variable, with the first parameter being the
global variable you would like to store in the EXPIREREF field, and
the second is the function name.
In this example, we want to be notified when a user's session
has expired, so we store the user id in $USERID, and make this
the value stored in the EXPIREREF field:
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
*/
if (!defined('_ADODB_LAYER')) {
include (dirname(__FILE__).'/adodb.inc.php');
}
if (!defined('ADODB_SESSION')) {
define('ADODB_SESSION',1);
/* if database time and system time is difference is greater than this, then give warning */
define('ADODB_SESSION_SYNCH_SECS',60);
/****************************************************************************************\
Global definitions
\****************************************************************************************/
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_EXPIRE_NOTIFY,
$ADODB_SESSION_CRC;
$ADODB_SESSION_USE_LOBS;
$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
if ($ADODB_SESS_LIFE <= 1) {
/* bug in PHP 4.0.3 pl 1 -- how about other versions? */
/* print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>"; */
$ADODB_SESS_LIFE=1440;
}
$ADODB_SESSION_CRC = false;
/* $ADODB_SESS_DEBUG = true; */
/* //////////////////////////////// */
/* SET THE FOLLOWING PARAMETERS */
/* //////////////////////////////// */
if (empty($ADODB_SESSION_DRIVER)) {
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='xphplens_2';
}
if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
$ADODB_SESSION_EXPIRE_NOTIFY = false;
}
/* Made table name configurable - by David Johnson [email protected] */
if (empty($ADODB_SESSION_TBL)){
$ADODB_SESSION_TBL = 'sessions';
}
/* defaulting $ADODB_SESSION_USE_LOBS */
if (!isset($ADODB_SESSION_USE_LOBS) || empty($ADODB_SESSION_USE_LOBS)) {
$ADODB_SESSION_USE_LOBS = false;
}
/*
$ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
$ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
$ADODB_SESS['user'] = $ADODB_SESSION_USER;
$ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
$ADODB_SESS['db'] = $ADODB_SESSION_DB;
$ADODB_SESS['life'] = $ADODB_SESS_LIFE;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['table'] = $ADODB_SESS_TBL;
*/
/****************************************************************************************\
Create the connection to the database.
If $ADODB_SESS_CONN already exists, reuse that connection
\****************************************************************************************/
function adodb_sess_open($save_path, $session_name,$persist=true)
{
GLOBAL $ADODB_SESS_CONN;
if (isset($ADODB_SESS_CONN)) return true;
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_DEBUG;
/* cannot use & below - do not know why... */
$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
if (!empty($ADODB_SESS_DEBUG)) {
$ADODB_SESS_CONN->debug = true;
ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
}
if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
if (!$ok) ADOConnection::outp( "<p>Session: connection failed</p>",false);
}
/****************************************************************************************\
Close the connection
\****************************************************************************************/
function adodb_sess_close()
{
global $ADODB_SESS_CONN;
if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
return true;
}
/****************************************************************************************\
Slurp in the session variables and return the serialized string
\****************************************************************************************/
function adodb_sess_read($key)
{
global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
if ($rs) {
if ($rs->EOF) {
$v = '';
} else
$v = rawurldecode(reset($rs->fields));
$rs->Close();
/* new optimization adodb 2.1 */
$ADODB_SESSION_CRC = strlen($v).crc32($v);
return $v;
}
return ''; /* thx to Jorma Tuomainen, webmaster#wizactive.com */
}
/****************************************************************************************\
Write the serialized data to a database.
If the data has not been modified since adodb_sess_read(), we do not write.
\****************************************************************************************/
function adodb_sess_write($key, $val)
{
global
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESSION_TBL,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_CRC,
$ADODB_SESSION_EXPIRE_NOTIFY,
$ADODB_SESSION_DRIVER, /* added */
$ADODB_SESSION_USE_LOBS; /* added */
$expiry = time() + $ADODB_SESS_LIFE;
/* crc32 optimization since adodb 2.1 */
/* now we only update expiry date, thx to sebastian thom in adodb 2.32 */
if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
if ($ADODB_SESS_DEBUG) echo "<p>Session: Only updating date - crc32 not changed</p>";
$qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
$rs = $ADODB_SESS_CONN->Execute($qry);
return true;
}
$val = rawurlencode($val);
$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
global $$var;
$arr['expireref'] = $$var;
}
if ($ADODB_SESSION_USE_LOBS === false) { /* no lobs, simply use replace() */
$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr, 'sesskey',$autoQuote = true);
if (!$rs) {
$err = $ADODB_SESS_CONN->ErrorMsg();
}
} else {
/* what value shall we insert/update for lob row? */
switch ($ADODB_SESSION_DRIVER) {
/* empty_clob or empty_lob for oracle dbs */
case "oracle":
case "oci8":
case "oci8po":
case "oci805":
$lob_value = sprintf("empty_%s()", strtolower($ADODB_SESSION_USE_LOBS));
break;
/* null for all other */
default:
$lob_value = "null";
break;
}
/* do we insert or update? => as for sesskey */
$res = $ADODB_SESS_CONN->Execute("select count(*) as cnt from $ADODB_SESSION_TBL where sesskey = '$key'");
if ($res && ($res->fields["CNT"] > 0)) {
$qry = sprintf("update %s set expiry = %d, data = %s where sesskey = '%s'", $ADODB_SESSION_TBL, $expiry, $lob_value, $key);
} else {
/* insert */
$qry = sprintf("insert into %s (sesskey, expiry, data) values ('%s', %d, %s)", $ADODB_SESSION_TBL, $key, $expiry, $lob_value);
}
$err = "";
$rs1 = $ADODB_SESS_CONN->Execute($qry);
if (!$rs1) {
$err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
}
$rs2 = $ADODB_SESS_CONN->UpdateBlob($ADODB_SESSION_TBL, 'data', $val, "sesskey='$key'", strtoupper($ADODB_SESSION_USE_LOBS));
if (!$rs2) {
$err .= $ADODB_SESS_CONN->ErrorMsg()."\n";
}
$rs = ($rs1 && $rs2) ? true : false;
}
if (!$rs) {
ADOConnection::outp( '<p>Session Replace: '.nl2br($err).'</p>',false);
} else {
/* bug in access driver (could be odbc?) means that info is not commited */
/* properly unless select statement executed in Win2000 */
if ($ADODB_SESS_CONN->databaseType == 'access')
$rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
}
return !empty($rs);
}
function adodb_sess_destroy($key)
{
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
$rs = $ADODB_SESS_CONN->Execute($qry);
}
return $rs ? true : false;
}
function adodb_sess_gc($maxlifetime)
{
global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
$ADODB_SESS_CONN->Execute($qry);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p><b>Garbage Collection</b>: $qry</p>");
}
/* suggested by Cameron, "GaM3R" <[email protected]> */
if (defined('ADODB_SESSION_OPTIMIZE')) {
global $ADODB_SESSION_DRIVER;
switch( $ADODB_SESSION_DRIVER ) {
case 'mysql':
case 'mysqlt':
$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
break;
case 'postgresql':
case 'postgresql7':
$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;
break;
}
if (!empty($opt_qry)) {
$ADODB_SESS_CONN->Execute($opt_qry);
}
}
$rs = $ADODB_SESS_CONN->SelectLimit('select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL,1);
if ($rs && !$rs->EOF) {
$dbt = reset($rs->fields);
$rs->Close();
$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbt);
$t = time();
if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
global $HTTP_SERVER_VARS;
$msg = "adodb-session.php: Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch: database=$dbt, webserver=".$t;
error_log($msg);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p>$msg</p>");
}
}
return true;
}
session_module_name('user');
session_set_save_handler(
"adodb_sess_open",
"adodb_sess_close",
"adodb_sess_read",
"adodb_sess_write",
"adodb_sess_destroy",
"adodb_sess_gc");
}
/* TEST SCRIPT -- UNCOMMENT */
if (0) {
GLOBAL $HTTP_SESSION_VARS;
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
ADOConnection::outp( "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>",false);
}
?>
+378 -378
View File
@@ -1,379 +1,379 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version of ADODB is available at http://php.weblogs.com/adodb
======================================================================
This file provides PHP4 session management using the ADODB database
wrapper library.
Example
=======
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
To force non-persistent connections, call adodb_session_open first before session_start():
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
adodb_session_open(false,false,false);
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
Installation
============
1. Create this table in your database (syntax might vary depending on your db):
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
EXPIREREF varchar(64),
DATA text not null,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
3. Recommended is PHP 4.0.6 or later. There are documented
session bugs in earlier versions of PHP.
4. If you want to receive notifications when a session expires, then
you can tag a session with an EXPIREREF, and before the session
record is deleted, we can call a function that will pass the EXPIREREF
as the first parameter, and the session key as the second parameter.
To do this, define a notification function, say NotifyFn:
function NotifyFn($expireref, $sesskey)
{
}
Then define a global variable, with the first parameter being the
global variable you would like to store in the EXPIREREF field, and
the second is the function name.
In this example, we want to be notified when a user's session
has expired, so we store the user id in $USERID, and make this
the value stored in the EXPIREREF field:
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
*/
if (!defined('_ADODB_LAYER')) {
include (dirname(__FILE__).'/adodb.inc.php');
}
if (!defined('ADODB_SESSION')) {
define('ADODB_SESSION',1);
/* if database time and system time is difference is greater than this, then give warning */
define('ADODB_SESSION_SYNCH_SECS',60);
/****************************************************************************************\
Global definitions
\****************************************************************************************/
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_EXPIRE_NOTIFY,
$ADODB_SESSION_CRC;
$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
if ($ADODB_SESS_LIFE <= 1) {
// bug in PHP 4.0.3 pl 1 -- how about other versions?
//print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>";
$ADODB_SESS_LIFE=1440;
}
$ADODB_SESSION_CRC = false;
//$ADODB_SESS_DEBUG = true;
//////////////////////////////////
/* SET THE FOLLOWING PARAMETERS */
//////////////////////////////////
if (empty($ADODB_SESSION_DRIVER)) {
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='xphplens_2';
}
if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
$ADODB_SESSION_EXPIRE_NOTIFY = false;
}
// Made table name configurable - by David Johnson [email protected]
if (empty($ADODB_SESSION_TBL)){
$ADODB_SESSION_TBL = 'sessions';
}
/*
$ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
$ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
$ADODB_SESS['user'] = $ADODB_SESSION_USER;
$ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
$ADODB_SESS['db'] = $ADODB_SESSION_DB;
$ADODB_SESS['life'] = $ADODB_SESS_LIFE;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['table'] = $ADODB_SESS_TBL;
*/
/****************************************************************************************\
Create the connection to the database.
If $ADODB_SESS_CONN already exists, reuse that connection
\****************************************************************************************/
function adodb_sess_open($save_path, $session_name,$persist=true)
{
GLOBAL $ADODB_SESS_CONN;
if (isset($ADODB_SESS_CONN)) return true;
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_DEBUG;
// cannot use & below - do not know why...
$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
if (!empty($ADODB_SESS_DEBUG)) {
$ADODB_SESS_CONN->debug = true;
ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
}
if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
if (!$ok) ADOConnection::outp( "<p>Session: connection failed</p>",false);
}
/****************************************************************************************\
Close the connection
\****************************************************************************************/
function adodb_sess_close()
{
global $ADODB_SESS_CONN;
if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
return true;
}
/****************************************************************************************\
Slurp in the session variables and return the serialized string
\****************************************************************************************/
function adodb_sess_read($key)
{
global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
if ($rs) {
if ($rs->EOF) {
$v = '';
} else
$v = rawurldecode(reset($rs->fields));
$rs->Close();
// new optimization adodb 2.1
$ADODB_SESSION_CRC = strlen($v).crc32($v);
return $v;
}
return ''; // thx to Jorma Tuomainen, webmaster#wizactive.com
}
/****************************************************************************************\
Write the serialized data to a database.
If the data has not been modified since adodb_sess_read(), we do not write.
\****************************************************************************************/
function adodb_sess_write($key, $val)
{
global
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESSION_TBL,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_CRC,
$ADODB_SESSION_EXPIRE_NOTIFY;
$expiry = time() + $ADODB_SESS_LIFE;
// crc32 optimization since adodb 2.1
// now we only update expiry date, thx to sebastian thom in adodb 2.32
if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
if ($ADODB_SESS_DEBUG) echo "<p>Session: Only updating date - crc32 not changed</p>";
$qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
$rs = $ADODB_SESS_CONN->Execute($qry);
return true;
}
$val = rawurlencode($val);
$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
global $$var;
$arr['expireref'] = $$var;
}
$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr,
'sesskey',$autoQuote = true);
if (!$rs) {
ADOConnection::outp( '<p>Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
} else {
// bug in access driver (could be odbc?) means that info is not commited
// properly unless select statement executed in Win2000
if ($ADODB_SESS_CONN->databaseType == 'access')
$rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
}
return !empty($rs);
}
function adodb_sess_destroy($key)
{
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
$rs = $ADODB_SESS_CONN->Execute($qry);
}
return $rs ? true : false;
}
function adodb_sess_gc($maxlifetime)
{
global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
$ADODB_SESS_CONN->Execute($qry);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p><b>Garbage Collection</b>: $qry</p>");
}
// suggested by Cameron, "GaM3R" <[email protected]>
if (defined('ADODB_SESSION_OPTIMIZE')) {
global $ADODB_SESSION_DRIVER;
switch( $ADODB_SESSION_DRIVER ) {
case 'mysql':
case 'mysqlt':
$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
break;
case 'postgresql':
case 'postgresql7':
$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;
break;
}
if (!empty($opt_qry)) {
$ADODB_SESS_CONN->Execute($opt_qry);
}
}
$rs = $ADODB_SESS_CONN->SelectLimit('select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL,1);
if ($rs && !$rs->EOF) {
$dbt = reset($rs->fields);
$rs->Close();
$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbt);
$t = time();
if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
global $HTTP_SERVER_VARS;
$msg = "adodb-session.php: Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch: database=$dbt, webserver=".$t;
error_log($msg);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p>$msg</p>");
}
}
return true;
}
session_module_name('user');
session_set_save_handler(
"adodb_sess_open",
"adodb_sess_close",
"adodb_sess_read",
"adodb_sess_write",
"adodb_sess_destroy",
"adodb_sess_gc");
}
/* TEST SCRIPT -- UNCOMMENT */
if (0) {
GLOBAL $HTTP_SESSION_VARS;
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
ADOConnection::outp( "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>",false);
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version of ADODB is available at http://php.weblogs.com/adodb
======================================================================
This file provides PHP4 session management using the ADODB database
wrapper library.
Example
=======
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
To force non-persistent connections, call adodb_session_open first before session_start():
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
adodb_sess_open(false,false,false);
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
Installation
============
1. Create this table in your database (syntax might vary depending on your db):
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
EXPIREREF varchar(64),
DATA text not null,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
3. Recommended is PHP 4.0.6 or later. There are documented
session bugs in earlier versions of PHP.
4. If you want to receive notifications when a session expires, then
you can tag a session with an EXPIREREF, and before the session
record is deleted, we can call a function that will pass the EXPIREREF
as the first parameter, and the session key as the second parameter.
To do this, define a notification function, say NotifyFn:
function NotifyFn($expireref, $sesskey)
{
}
Then define a global variable, with the first parameter being the
global variable you would like to store in the EXPIREREF field, and
the second is the function name.
In this example, we want to be notified when a user's session
has expired, so we store the user id in $USERID, and make this
the value stored in the EXPIREREF field:
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
*/
if (!defined('_ADODB_LAYER')) {
include (dirname(__FILE__).'/adodb.inc.php');
}
if (!defined('ADODB_SESSION')) {
define('ADODB_SESSION',1);
/* if database time and system time is difference is greater than this, then give warning */
define('ADODB_SESSION_SYNCH_SECS',60);
/****************************************************************************************\
Global definitions
\****************************************************************************************/
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_EXPIRE_NOTIFY,
$ADODB_SESSION_CRC;
$ADODB_SESS_LIFE = ini_get('session.gc_maxlifetime');
if ($ADODB_SESS_LIFE <= 1) {
/* bug in PHP 4.0.3 pl 1 -- how about other versions? */
/* print "<h3>Session Error: PHP.INI setting <i>session.gc_maxlifetime</i>not set: $ADODB_SESS_LIFE</h3>"; */
$ADODB_SESS_LIFE=1440;
}
$ADODB_SESSION_CRC = false;
/* $ADODB_SESS_DEBUG = true; */
/* //////////////////////////////// */
/* SET THE FOLLOWING PARAMETERS */
/* //////////////////////////////// */
if (empty($ADODB_SESSION_DRIVER)) {
$ADODB_SESSION_DRIVER='mysql';
$ADODB_SESSION_CONNECT='localhost';
$ADODB_SESSION_USER ='root';
$ADODB_SESSION_PWD ='';
$ADODB_SESSION_DB ='xphplens_2';
}
if (empty($ADODB_SESSION_EXPIRE_NOTIFY)) {
$ADODB_SESSION_EXPIRE_NOTIFY = false;
}
/* Made table name configurable - by David Johnson [email protected] */
if (empty($ADODB_SESSION_TBL)){
$ADODB_SESSION_TBL = 'sessions';
}
/*
$ADODB_SESS['driver'] = $ADODB_SESSION_DRIVER;
$ADODB_SESS['connect'] = $ADODB_SESSION_CONNECT;
$ADODB_SESS['user'] = $ADODB_SESSION_USER;
$ADODB_SESS['pwd'] = $ADODB_SESSION_PWD;
$ADODB_SESS['db'] = $ADODB_SESSION_DB;
$ADODB_SESS['life'] = $ADODB_SESS_LIFE;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['debug'] = $ADODB_SESS_DEBUG;
$ADODB_SESS['table'] = $ADODB_SESS_TBL;
*/
/****************************************************************************************\
Create the connection to the database.
If $ADODB_SESS_CONN already exists, reuse that connection
\****************************************************************************************/
function adodb_sess_open($save_path, $session_name,$persist=true)
{
GLOBAL $ADODB_SESS_CONN;
if (isset($ADODB_SESS_CONN)) return true;
GLOBAL $ADODB_SESSION_CONNECT,
$ADODB_SESSION_DRIVER,
$ADODB_SESSION_USER,
$ADODB_SESSION_PWD,
$ADODB_SESSION_DB,
$ADODB_SESS_DEBUG;
/* cannot use & below - do not know why... */
$ADODB_SESS_CONN = ADONewConnection($ADODB_SESSION_DRIVER);
if (!empty($ADODB_SESS_DEBUG)) {
$ADODB_SESS_CONN->debug = true;
ADOConnection::outp( " conn=$ADODB_SESSION_CONNECT user=$ADODB_SESSION_USER pwd=$ADODB_SESSION_PWD db=$ADODB_SESSION_DB ");
}
if ($persist) $ok = $ADODB_SESS_CONN->PConnect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
else $ok = $ADODB_SESS_CONN->Connect($ADODB_SESSION_CONNECT,
$ADODB_SESSION_USER,$ADODB_SESSION_PWD,$ADODB_SESSION_DB);
if (!$ok) ADOConnection::outp( "<p>Session: connection failed</p>",false);
}
/****************************************************************************************\
Close the connection
\****************************************************************************************/
function adodb_sess_close()
{
global $ADODB_SESS_CONN;
if ($ADODB_SESS_CONN) $ADODB_SESS_CONN->Close();
return true;
}
/****************************************************************************************\
Slurp in the session variables and return the serialized string
\****************************************************************************************/
function adodb_sess_read($key)
{
global $ADODB_SESS_CONN,$ADODB_SESSION_TBL,$ADODB_SESSION_CRC;
$rs = $ADODB_SESS_CONN->Execute("SELECT data FROM $ADODB_SESSION_TBL WHERE sesskey = '$key' AND expiry >= " . time());
if ($rs) {
if ($rs->EOF) {
$v = '';
} else
$v = rawurldecode(reset($rs->fields));
$rs->Close();
/* new optimization adodb 2.1 */
$ADODB_SESSION_CRC = strlen($v).crc32($v);
return $v;
}
return ''; /* thx to Jorma Tuomainen, webmaster#wizactive.com */
}
/****************************************************************************************\
Write the serialized data to a database.
If the data has not been modified since adodb_sess_read(), we do not write.
\****************************************************************************************/
function adodb_sess_write($key, $val)
{
global
$ADODB_SESS_CONN,
$ADODB_SESS_LIFE,
$ADODB_SESSION_TBL,
$ADODB_SESS_DEBUG,
$ADODB_SESSION_CRC,
$ADODB_SESSION_EXPIRE_NOTIFY;
$expiry = time() + $ADODB_SESS_LIFE;
/* crc32 optimization since adodb 2.1 */
/* now we only update expiry date, thx to sebastian thom in adodb 2.32 */
if ($ADODB_SESSION_CRC !== false && $ADODB_SESSION_CRC == strlen($val).crc32($val)) {
if ($ADODB_SESS_DEBUG) echo "<p>Session: Only updating date - crc32 not changed</p>";
$qry = "UPDATE $ADODB_SESSION_TBL SET expiry=$expiry WHERE sesskey='$key' AND expiry >= " . time();
$rs = $ADODB_SESS_CONN->Execute($qry);
return true;
}
$val = rawurlencode($val);
$arr = array('sesskey' => $key, 'expiry' => $expiry, 'data' => $val);
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
$var = reset($ADODB_SESSION_EXPIRE_NOTIFY);
global $$var;
$arr['expireref'] = $$var;
}
$rs = $ADODB_SESS_CONN->Replace($ADODB_SESSION_TBL,$arr,
'sesskey',$autoQuote = true);
if (!$rs) {
ADOConnection::outp( '<p>Session Replace: '.$ADODB_SESS_CONN->ErrorMsg().'</p>',false);
} else {
/* bug in access driver (could be odbc?) means that info is not commited */
/* properly unless select statement executed in Win2000 */
if ($ADODB_SESS_CONN->databaseType == 'access')
$rs = $ADODB_SESS_CONN->Execute("select sesskey from $ADODB_SESSION_TBL WHERE sesskey='$key'");
}
return !empty($rs);
}
function adodb_sess_destroy($key)
{
global $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE sesskey = '$key'";
$rs = $ADODB_SESS_CONN->Execute($qry);
}
return $rs ? true : false;
}
function adodb_sess_gc($maxlifetime)
{
global $ADODB_SESS_DEBUG, $ADODB_SESS_CONN, $ADODB_SESSION_TBL,$ADODB_SESSION_EXPIRE_NOTIFY;
if ($ADODB_SESSION_EXPIRE_NOTIFY) {
reset($ADODB_SESSION_EXPIRE_NOTIFY);
$fn = next($ADODB_SESSION_EXPIRE_NOTIFY);
$savem = $ADODB_SESS_CONN->SetFetchMode(ADODB_FETCH_NUM);
$rs = $ADODB_SESS_CONN->Execute("SELECT expireref,sesskey FROM $ADODB_SESSION_TBL WHERE expiry < " . time());
$ADODB_SESS_CONN->SetFetchMode($savem);
if ($rs) {
$ADODB_SESS_CONN->BeginTrans();
while (!$rs->EOF) {
$ref = $rs->fields[0];
$key = $rs->fields[1];
$fn($ref,$key);
$del = $ADODB_SESS_CONN->Execute("DELETE FROM $ADODB_SESSION_TBL WHERE sesskey='$key'");
$rs->MoveNext();
}
$ADODB_SESS_CONN->CommitTrans();
}
} else {
$qry = "DELETE FROM $ADODB_SESSION_TBL WHERE expiry < " . time();
$ADODB_SESS_CONN->Execute($qry);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p><b>Garbage Collection</b>: $qry</p>");
}
/* suggested by Cameron, "GaM3R" <[email protected]> */
if (defined('ADODB_SESSION_OPTIMIZE')) {
global $ADODB_SESSION_DRIVER;
switch( $ADODB_SESSION_DRIVER ) {
case 'mysql':
case 'mysqlt':
$opt_qry = 'OPTIMIZE TABLE '.$ADODB_SESSION_TBL;
break;
case 'postgresql':
case 'postgresql7':
$opt_qry = 'VACUUM '.$ADODB_SESSION_TBL;
break;
}
if (!empty($opt_qry)) {
$ADODB_SESS_CONN->Execute($opt_qry);
}
}
$rs = $ADODB_SESS_CONN->SelectLimit('select '.$ADODB_SESS_CONN->sysTimeStamp.' from '. $ADODB_SESSION_TBL,1);
if ($rs && !$rs->EOF) {
$dbt = reset($rs->fields);
$rs->Close();
$dbt = $ADODB_SESS_CONN->UnixTimeStamp($dbt);
$t = time();
if (abs($dbt - $t) >= ADODB_SESSION_SYNCH_SECS) {
global $HTTP_SERVER_VARS;
$msg = "adodb-session.php: Server time for webserver {$HTTP_SERVER_VARS['HTTP_HOST']} not in synch: database=$dbt, webserver=".$t;
error_log($msg);
if ($ADODB_SESS_DEBUG) ADOConnection::outp("<p>$msg</p>");
}
}
return true;
}
session_module_name('user');
session_set_save_handler(
"adodb_sess_open",
"adodb_sess_close",
"adodb_sess_read",
"adodb_sess_write",
"adodb_sess_destroy",
"adodb_sess_gc");
}
/* TEST SCRIPT -- UNCOMMENT */
if (0) {
GLOBAL $HTTP_SESSION_VARS;
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
ADOConnection::outp( "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>",false);
}
?>
+36 -36
View File
@@ -1,5 +1,4 @@
<?php
/**
ADOdb Date Library, part of the ADOdb abstraction library
Download: http://php.weblogs.com/adodb_date_time_library
@@ -238,7 +237,7 @@ if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1);
function adodb_date_test_date($y1,$m)
{
//print " $y1/$m ";
/* print " $y1/$m "; */
$t = adodb_mktime(0,0,0,$m,13,$y1);
if ("$y1-$m-13 00:00:00" != adodb_date('Y-n-d H:i:s',$t)) {
print "<b>$y1 error</b><br>";
@@ -257,12 +256,12 @@ function adodb_date_test()
set_time_limit(0);
$fail = false;
// This flag disables calling of PHP native functions, so we can properly test the code
/* This flag disables calling of PHP native functions, so we can properly test the code */
if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1);
print "<p>Testing gregorian <=> julian conversion<p>";
$t = adodb_mktime(0,0,0,10,11,1492);
//http://www.holidayorigins.com/html/columbus_day.html - Friday check
/* http://www.holidayorigins.com/html/columbus_day.html - Friday check */
if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing<br>';
$t = adodb_mktime(0,0,0,2,29,1500);
@@ -303,7 +302,7 @@ function adodb_date_test()
if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950<br>";
if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990<br>";
// Test string formating
/* Test string formating */
print "<p>Testing date formating</p>";
$fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C822 r s t U w y Y z Z 2003';
$s1 = date($fmt,0);
@@ -317,7 +316,7 @@ function adodb_date_test()
$ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000);
$s1 = date($fmt,$ts);
$s2 = adodb_date($fmt,$ts);
//print "$s1 <br>$s2 <p>";
/* print "$s1 <br>$s2 <p>"; */
$pos = strcmp($s1,$s2);
if (($s1) != ($s2)) {
@@ -346,7 +345,7 @@ function adodb_date_test()
}
}
// Test generation of dates outside 1901-2038
/* Test generation of dates outside 1901-2038 */
print "<p>Testing random dates between 100 and 4000</p>";
adodb_date_test_date(100,1);
for ($i=100; --$i >= 0;) {
@@ -365,8 +364,8 @@ function adodb_date_test()
$max = 365*$yrs*86400;
$lastyear = 0;
// we generate a timestamp, convert it to a date, and convert it back to a timestamp
// and check if the roundtrip broke the original timestamp value.
/* we generate a timestamp, convert it to a date, and convert it back to a timestamp */
/* and check if the roundtrip broke the original timestamp value. */
print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: ";
for ($max += $i; $i < $max; $i += $offset) {
@@ -437,7 +436,7 @@ function _adodb_is_leap_year($year)
if ($year % 400 == 0) {
return true;
// if gregorian calendar (>1582), century not-divisible by 400 is not leap
/* if gregorian calendar (>1582), century not-divisible by 400 is not leap */
} else if ($year > 1582 && $year % 100 == 0 ) {
return false;
}
@@ -472,8 +471,8 @@ function adodb_year_digit_check($y)
$c0 = $century - 1;
}
$c1 *= 100;
// if 2-digit year is less than 30 years in future, set it to this century
// otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
/* if 2-digit year is less than 30 years in future, set it to this century */
/* otherwise if more than 30 years in future, then we set 2-digit year to the prev century. */
if (($y + $c1) < $yr+30) $y = $y + $c1;
else $y = $y + $c0*100;
}
@@ -499,8 +498,8 @@ function adodb_getdate($d=false,$fast=false)
{
if ($d === false) return getdate();
if (!defined('ADODB_TEST_DATES')) {
if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
if ((abs($d) <= 0x7FFFFFFF)) { /* check if number in 32-bit signed range */
if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) /* if windows, must be +ve integer */
return @getdate($d);
}
}
@@ -520,15 +519,15 @@ function _adodb_getdate($origd=false,$fast=false,$is_gmt=false)
$_hour_power = 3600;
$_min_power = 60;
if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction
if ($d < -12219321600) $d -= 86400*10; /* if 15 Oct 1582 or earlier, gregorian correction */
$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31);
$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31);
if ($d < 0) {
$origd = $d;
// The valid range of a 32bit signed timestamp is typically from
// Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT
/* The valid range of a 32bit signed timestamp is typically from */
/* Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT */
for ($a = 1970 ; --$a >= 0;) {
$lastd = $d;
@@ -642,8 +641,8 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
{
if ($d === false) return date($fmt);
if (!defined('ADODB_TEST_DATES')) {
if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range
if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer
if ((abs($d) <= 0x7FFFFFFF)) { /* check if number in 32-bit signed range */
if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) /* if windows, must be +ve integer */
return @date($fmt,$d);
}
}
@@ -666,10 +665,10 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
*/
for ($i=0; $i < $max; $i++) {
switch($fmt[$i]) {
case 'T': $dates .= date('T',100000);break;
// YEAR
case 'T': $dates .= date('T');break;
/* YEAR */
case 'L': $dates .= $arr['leap'] ? '1' : '0'; break;
case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
case 'r': /* Thu, 21 Dec 2000 16:01:07 +0200 */
$dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', '
. ($day<10?' '.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' ';
@@ -685,12 +684,12 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
case 'Y': $dates .= $year; break;
case 'y': $dates .= substr($year,strlen($year)-2,2); break;
// MONTH
/* MONTH */
case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break;
case 'n': $dates .= $month; break;
case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break;
case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break;
// DAY
/* DAY */
case 't': $dates .= $arr['ndays']; break;
case 'z': $dates .= $arr['yday']; break;
case 'w': $dates .= adodb_dow($year,$month,$day); break;
@@ -706,7 +705,7 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
else $dates .= 'th';
break;
// HOUR
/* HOUR */
case 'Z':
$dates .= ($is_gmt) ? 0 : -adodb_get_gmt_different(); break;
case 'O':
@@ -740,13 +739,13 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
}
$dates .= $hh;
break;
// MINUTES
/* MINUTES */
case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break;
// SECONDS
/* SECONDS */
case 'U': $dates .= $d; break;
case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break;
// AM/PM
// Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM
/* AM/PM */
/* Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM */
case 'a':
if ($hour>=12) $dates .= 'pm';
else $dates .= 'am';
@@ -757,7 +756,7 @@ function adodb_date($fmt,$d=false,$is_gmt=false)
break;
default:
$dates .= $fmt[$i]; break;
// ESCAPE
/* ESCAPE */
case "\\":
$i++;
if ($i < $max) $dates .= $fmt[$i];
@@ -781,9 +780,10 @@ function adodb_gmmktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false)
Note that $is_dst is not implemented and is ignored.
*/
function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false)
{ if (!defined('ADODB_TEST_DATES')) {
// for windows, we don't check 1970 because with timezone differences,
// 1 Jan 1970 could generate negative timestamp, which is illegal
{
if (!defined('ADODB_TEST_DATES')) {
/* for windows, we don't check 1970 because with timezone differences, */
/* 1 Jan 1970 could generate negative timestamp, which is illegal */
if (!defined('ADODB_NO_NEGATIVE_TS') || ($year >= 1971))
if (1901 < $year && $year < 2038)
return @mktime($hr,$min,$sec,$mon,$day,$year);
@@ -858,10 +858,10 @@ function adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst=false,$is_gmt=false)
$_day_time = $hr * $_hour_power + $min * $_min_power + $sec;
$_day_time = $_day_power - $_day_time;
$ret = -( $_total_date * $_day_power + $_day_time - $gmt_different);
if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction
else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582.
if ($ret < -12220185600) $ret += 10*86400; /* if earlier than 5 Oct 1582 - gregorian correction */
else if ($ret < -12219321600) $ret = -12219321600; /* if in limbo, reset to 15 Oct 1582. */
}
//print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret;
/* print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; */
return $ret;
}
+722
View File
@@ -0,0 +1,722 @@
<?PHP
/* ******************************************************************************
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*******************************************************************************/
/**
* xmlschema is a class that allows the user to quickly and easily
* build a database on any ADOdb-supported platform using a simple
* XML schema.
*
* @author Richard Tango-Lowy
* @version $Revision$
* @copyright Copyright (c) 2003 ars Cognita Inc., all rights reserved
*
* @package xmlschema
*/
/**
* Include the main ADODB library
*/
if (!defined( '_ADODB_LAYER' ) ) {
require( 'adodb.inc.php' );
}
/**
* Creates a table object in ADOdb's datadict format
*
* This class stores information about a database table. As charactaristics
* of the table are loaded from the external source, methods and properties
* of this class are used to build up the table description in ADOdb's
* datadict format.
*
* @package xmlschema
* @access private
*/
class dbTable {
/**
* @var string Table name
*/
var $tableName;
/**
* @var array Field specifier: Meta-information about each field
*/
var $fieldSpec;
/**
* @var array Table options: Table-level options
*/
var $tableOpts;
/**
* @var string Field index: Keeps track of which field is currently being processed
*/
var $currentField;
/**
* Constructor. Iniitializes a new table object.
*
* @param string $name Table name
*/
function dbTable( $name ) {
$this->tableName = $name;
}
/**
* Adds a field to a table object
*
* $name is the name of the table to which the field should be added.
* $type is an ADODB datadict field type. The following field types
* are supported as of ADODB 3.40:
* - C: varchar
* - X: CLOB (character large object) or largest varchar size
* if CLOB is not supported
* - C2: Multibyte varchar
* - X2: Multibyte CLOB
* - B: BLOB (binary large object)
* - D: Date (some databases do not support this, and we return a datetime type)
* - T: Datetime or Timestamp
* - L: Integer field suitable for storing booleans (0 or 1)
* - I: Integer (mapped to I4)
* - I1: 1-byte integer
* - I2: 2-byte integer
* - I4: 4-byte integer
* - I8: 8-byte integer
* - F: Floating point number
* - N: Numeric or decimal number
*
* @param string $name Name of the table to which the field will be added.
* @param string $type ADODB datadict field type.
* @param string $size Field size
* @param array $opts Field options array
* @return array Field specifier array
*/
function addField( $name, $type, $size = NULL, $opts = NULL ) {
/* Set the field index so we know where we are */
$this->currentField = $name;
/* Set the field type (required) */
$this->fieldSpec[$name]['TYPE'] = $type;
/* Set the field size (optional) */
if( isset( $size ) ) {
$this->fieldSpec[$name]['SIZE'] = $size;
}
/* Set the field options */
if( isset( $opts ) ) $this->fieldSpec[$name]['OPTS'] = $opts;
/* Return array containing field specifier */
return $this->fieldSpec;
}
/**
* Adds a field option to the current field specifier
*
* This method adds a field option allowed by the ADOdb datadict
* and appends it to the given field.
*
* @param string $field Field name
* @param string $opt ADOdb field option
* @param mixed $value Field option value
* @return array Field specifier array
*/
function addFieldOpt( $field, $opt, $value = NULL ) {
/* Add the option to the field specifier */
if( $value === NULL ) { /* No value, so add only the option */
$this->fieldSpec[$field]['OPTS'][] = $opt;
} else { /* Add the option and value */
$this->fieldSpec[$field]['OPTS'][] = array( "$opt" => "$value" );
}
/* Return array containing field specifier */
return $this->fieldSpec;
}
/**
* Adds an option to the table
*
*This method takes a comma-separated list of table-level options
* and appends them to the table object.
*
* @param string $opt Table option
* @return string Option list
*/
function addTableOpt( $opt ) {
$optlist = &$this->tableOpts;
$optlist ? $optlist .= ", $opt" : $optlist = $opt;
/* Return the options list */
return $optlist;
}
/**
* Generates the SQL that will create the table in the database
*
* Returns SQL that will create the table represented by the object.
*
* @param object $dict ADOdb data dictionary
* @return array Array containing table creation SQL
*/
function create( $dict ) {
/* Loop through the field specifier array, building the associative array for the field options */
$fldarray = array();
$i = 0;
foreach( $this->fieldSpec as $field => $finfo ) {
$i++;
/* Set an empty size if it isn't supplied */
if( !isset( $finfo['SIZE'] ) ) $finfo['SIZE'] = '';
/* Initialize the field array with the type and size */
$fldarray[$i] = array( $field, $finfo['TYPE'], $finfo['SIZE'] );
/* Loop through the options array and add the field options. */
$opts = $finfo['OPTS'];
if( $opts ) {
foreach( $finfo['OPTS'] as $opt ) {
if( is_array( $opt ) ) { /* Option has an argument. */
$key = key( $opt );
$value = $opt[key( $opt ) ];
$fldarray[$i][$key] = $value;
} else { /* Option doesn't have arguments */
array_push( $fldarray[$i], $opt );
}
}
}
}
/* Build table array */
$sqlArray = $dict->CreateTableSQL( $this->tableName, $fldarray, $this->tableOpts );
/* Return the array containing the SQL to create the table */
return $sqlArray;
}
/**
* Destructor
*/
function destroy() {
unset( $this );
}
}
/**
* Creates an index object in ADOdb's datadict format
*
* This class stores information about a database index. As charactaristics
* of the index are loaded from the external source, methods and properties
* of this class are used to build up the index description in ADOdb's
* datadict format.
*
* @package xmlschema
* @access private
*/
class dbIndex {
/**
* @var string Index name
*/
var $indexName;
/**
* @var string Name of the table this index is attached to
*/
var $tableName;
/**
* @var array Indexed fields: Table columns included in this index
*/
var $fields;
/**
* Constructor. Initialize the index and table names.
*
* @param string $name Index name
* @param string $table Name of indexed table
*/
function dbIndex( $name, $table ) {
$this->indexName = $name;
$this->tableName = $table;
}
/**
* Adds a field to the index
*
* This method adds the specified column to an index.
*
* @param string $name Field name
* @return string Field list
*/
function addField( $name ) {
$fieldlist = &$this->fields;
$fieldlist ? $fieldlist .=" , $name" : $fieldlist = $name;
/* Return the field list */
return $fieldlist;
}
/**
* Generates the SQL that will create the index in the database
*
* Returns SQL that will create the index represented by the object.
*
* @param object $dict ADOdb data dictionary object
* @return array Array containing index creation SQL
*/
function create( $dict ) {
/* Build table array */
$sqlArray = $dict->CreateIndexSQL( $this->indexName, $this->tableName, $this->fields );
/* Return the array containing the SQL to create the table */
return $sqlArray;
}
/**
* Destructor
*/
function destroy() {
unset( $this );
}
}
/**
* Creates the SQL to execute a list of provided SQL queries
*
* This class compiles a list of SQL queries specified in the external file.
*
* @package xmlschema
* @access private
*/
class dbQuerySet {
/**
* @var array List of SQL queries
*/
var $querySet;
/**
* @var string String used to build of a query line by line
*/
var $query;
/**
* Constructor. Initializes the queries array
*/
function dbQuerySet() {
$this->querySet = array();
$this->query = '';
}
/**
* Appends a line to a query that is being built line by line
*
* $param string $data Line of SQL data or NULL to initialize a new query
*/
function buildQuery( $data = NULL ) {
isset( $data ) ? $this->query .= " " . trim( $data ) : $this->query = '';
}
/**
* Adds a completed query to the query list
*
* @return string SQL of added query
*/
function addQuery() {
/* Push the query onto the query set array */
$finishedQuery = $this->query;
array_push( $this->querySet, $finishedQuery );
/* Return the query set array */
return $finishedQuery;
}
/**
* Creates and returns the current query set
*
* @return array Query set
*/
function create() {
return $this->querySet;
}
/**
* Destructor
*/
function destroy() {
unset( $this );
}
}
/**
* Loads and parses an XML file, creating an array of "ready-to-run" SQL statements
*
* This class is used to load and parse the XML file, to create an array of SQL statements
* that can be used to build a database, and to build the database using the SQL array.
*
* @package xmlschema
*/
class adoSchema {
/**
* @var array Array containing SQL queries to generate all objects
*/
var $sqlArray;
/**
* @var object XML Parser object
*/
var $xmlParser;
/**
* @var object ADOdb connection object
*/
var $dbconn;
/**
* @var string Database type (platform)
*/
var $dbType;
/**
* @var object ADOdb Data Dictionary
*/
var $dict;
/**
* @var object Temporary dbTable object
* @access private
*/
var $table;
/**
* @var object Temporary dbIndex object
* @access private
*/
var $index;
/**
* @var object Temporary dbQuerySet object
* @access private
*/
var $querySet;
/**
* @var string Current XML element
* @access private
*/
var $currentElement;
/**
* @var long Original Magic Quotes Runtime value
* @access private
*/
var $mgq;
/**
* Constructor. Initializes the xmlschema object
*
* @param object $dbconn ADOdb connection object
*/
function adoSchema( $dbconn ) {
/* Initialize the environment */
$this->mgq = get_magic_quotes_runtime();
set_magic_quotes_runtime(0);
$this->dbconn = &$dbconn;
$this->dbType = $dbconn->databaseType;
$this->sqlArray = array();
/* Create an ADOdb dictionary object */
$this->dict = NewDataDictionary( $dbconn );
}
/**
* Loads and parses an XML file
*
* This method accepts a path to an xmlschema-compliant XML file,
* loads it, parses it, and uses it to create the SQL to generate the objects
* described by the XML file.
*
* @param string $file XML file
* @return array Array of SQL queries, ready to execute
*/
function ParseSchema( $file ) {
/* Create the parser */
$this->xmlParser = &$xmlParser;
$xmlParser = xml_parser_create();
xml_set_object( $xmlParser, &$this );
/* Initialize the XML callback functions */
xml_set_element_handler( $xmlParser, "_xmlcb_startElement", "_xmlcb_endElement" );
xml_set_character_data_handler( $xmlParser, "_xmlcb_cData" );
/* Open the file */
if( !( $fp = fopen( $file, "r" ) ) ) {
die( "Unable to open file" );
}
/* Process the file */
while( $data = fread( $fp, 4096 ) ) {
if( !xml_parse( $xmlParser, $data, feof( $fp ) ) ) {
die( sprint( "XML error: %s at line %d",
xml_error_string( xml_get_error_code( $xmlParser ) ),
xml_get_current_line_number( $xmlParser ) ) );
}
}
/* Return the array of queries */
return $this->sqlArray;
}
/**
* Loads a schema into the database
*
* Accepts an array of SQL queries generated by the parser
* and executes them.
*
* @param array $sqlArray Array of SQL statements
* @param boolean $continueOnErr Don't fail out if an error is encountered
* @return integer 0 if failed, 1 if errors, 2 if successful
*/
function ExecuteSchema( $sqlArray, $continueOnErr = TRUE ) {
$err = $this->dict->ExecuteSQLArray( $sqlArray, $continueOnErr );
/* Return the success code */
return $err;
}
/**
* XML Callback to process start elements
*
* @access private
*/
function _xmlcb_startElement( $parser, $name, $attrs ) {
$dbType = $this->dbType;
if( isset( $this->table ) ) $table = &$this->table;
if( isset( $this->index ) ) $index = &$this->index;
if( isset( $this->querySet ) ) $querySet = &$this->querySet;
$this->currentElement = $name;
/* Process the element. Ignore unimportant elements. */
if( in_array( trim( $name ), array( "SCHEMA", "DESCR", "COL", "CONSTRAINT" ) ) ) {
return FALSE;
}
switch( $name ) {
case "TABLE": /* Table element */
if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) {
$this->table = new dbTable( $attrs['NAME'] );
} else {
unset( $this->table );
}
break;
case "FIELD": /* Table field */
if( isset( $this->table ) ) {
$fieldName = $attrs['NAME'];
$fieldType = $attrs['TYPE'];
isset( $attrs['SIZE'] ) ? $fieldSize = $attrs['SIZE'] : $fieldSize = NULL;
isset( $attrs['OPTS'] ) ? $fieldOpts = $attrs['OPTS'] : $fieldOpts = NULL;
$this->table->addField( $fieldName, $fieldType, $fieldSize, $fieldOpts );
}
break;
case "KEY": /* Table field option */
if( isset( $this->table ) ) {
$this->table->addFieldOpt( $this->table->currentField, 'KEY' );
}
break;
case "NOTNULL": /* Table field option */
if( isset( $this->table ) ) {
$this->table->addFieldOpt( $this->table->currentField, 'NOTNULL' );
}
break;
case "AUTOINCREMENT": /* Table field option */
if( isset( $this->table ) ) {
$this->table->addFieldOpt( $this->table->currentField, 'AUTOINCREMENT' );
}
break;
case "DEFAULT": /* Table field option */
if( isset( $this->table ) ) {
$this->table->addFieldOpt( $this->table->currentField, 'DEFAULT', $attrs['VALUE'] );
}
break;
case "INDEX": /* Table index */
if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) {
$this->index = new dbIndex( $attrs['NAME'], $attrs['TABLE'] );
} else {
if( isset( $this->index ) ) unset( $this->index );
}
break;
case "SQL": /* Freeform SQL queryset */
if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) {
$this->querySet = new dbQuerySet( $attrs );
} else {
if( isset( $this->querySet ) ) unset( $this->querySet );
}
break;
case "QUERY": /* Queryset SQL query */
if( isset( $this->querySet ) ) {
/* Ignore this query set if a platform is specified and it's different than the */
/* current connection platform. */
if( $this->supportedPlatform( $attrs['PLATFORM'] ) ) {
$this->querySet->buildQuery();
} else {
if( isset( $this->querySet->query ) ) unset( $this->querySet->query );
}
}
break;
default:
print "OPENING ELEMENT '$name'<BR/>\n";
}
}
/**
* XML Callback to process cDATA elements
*
* @access private
*/
function _xmlcb_cData( $parser, $data ) {
$element = &$this->currentElement;
if( trim( $data ) == "" ) return;
/* Process the data depending on the element */
switch( $element ) {
case "COL": /* Index column */
if( isset( $this->index ) ) $this->index->addField( $data );
break;
case "DESCR": /* Description element */
/* Display the description information */
if( isset( $this->table ) ) {
$name = "({$this->table->tableName}): ";
} elseif( isset( $this->index ) ) {
$name = "({$this->index->indexName}): ";
} else {
$name = "";
}
print "<LI> $name $data\n";
break;
case "QUERY": /* Query SQL data */
if( isset( $this->querySet ) and isset( $this->querySet->query ) ) $this->querySet->buildQuery( $data );
break;
case "CONSTRAINT": /* Table constraint */
if( isset( $this->table ) ) $this->table->addTableOpt( $data );
break;
default:
print "<UL><LI>CDATA ($element) $data</UL>\n";
}
}
/**
* XML Callback to process end elements
*
* @access private
*/
function _xmlcb_endElement( $parser, $name ) {
/* Process the element. Ignore unimportant elements. */
if( in_array( trim( $name ),
array( "SCHEMA", "DESCR", "KEY", "AUTOINCREMENT", "FIELD",
"DEFAULT", "NOTNULL", "CONSTRAINT", "COL" ) ) ) {
return FALSE;
}
switch( trim( $name ) ) {
case "TABLE": /* Table element */
if( isset( $this->table ) ) {
$tableSQL = $this->table->create( $this->dict );
array_push( $this->sqlArray, $tableSQL[0] );
$this->table->destroy();
}
break;
case "INDEX": /* Index element */
if( isset( $this->index ) ) {
$indexSQL = $this->index->create( $this->dict );
array_push( $this->sqlArray, $indexSQL[0] );
$this->index->destroy();
}
break;
case "QUERY": /* Queryset element */
if( isset( $this->querySet ) and isset( $this->querySet->query ) ) $this->querySet->addQuery();
break;
case "SQL": /* Query SQL element */
if( isset( $this->querySet ) ) {
$querySQL = $this->querySet->create();
$this->sqlArray = array_merge( $this->sqlArray, $querySQL );;
$this->querySet->destroy();
}
break;
default:
print "<LI>CLOSING $name</UL>\n";
}
}
/**
* Checks if element references a specific platform
*
* Returns TRUE is no platform is specified or if we are currently
* using the specified platform.
*
* @param string $platform Requested platform
* @return boolean TRUE if platform check succeeds
*
* @access private
*/
function supportedPlatform( $platform = NULL ) {
$dbType = $this->dbType;
$regex = "/^(\w*\|)*" . $dbType . "(\|\w*)*$/";
if( !isset( $platform ) or
preg_match( $regex, $platform ) ) {
return TRUE;
} else {
return FALSE;
}
}
/**
* Destructor
*/
function Destroy() {
xml_parser_free( $this->xmlParser );
set_magic_quotes_runtime( $this->mgq );
unset( $this );
}
}
?>
Binary file not shown.
+3354 -627
View File
File diff suppressed because it is too large Load Diff
+63 -63
View File
@@ -1,64 +1,64 @@
<?php
// Session Encryption by Ari Kuorikoski <[email protected]>
class MD5Crypt{
function keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++){
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function Encrypt($txt,$key)
{
srand((double)microtime()*1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($encrypt_key,$ctr,1) .
(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
$ctr++;
}
return base64_encode($this->keyED($tmp,$key));
}
function Decrypt($txt,$key)
{
$txt = $this->keyED(base64_decode($txt),$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++){
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
function RandPass()
{
$randomPassword = "";
srand((double)microtime()*1000000);
for($i=0;$i<8;$i++)
{
$randnumber = rand(48,120);
while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))
{
$randnumber = rand(48,120);
}
$randomPassword .= chr($randnumber);
}
return $randomPassword;
}
}
<?php
/* Session Encryption by Ari Kuorikoski <[email protected]> */
class MD5Crypt{
function keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++){
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
function Encrypt($txt,$key)
{
srand((double)microtime()*1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key)) $ctr=0;
$tmp.= substr($encrypt_key,$ctr,1) .
(substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
$ctr++;
}
return base64_encode($this->keyED($tmp,$key));
}
function Decrypt($txt,$key)
{
$txt = $this->keyED(base64_decode($txt),$key);
$tmp = "";
for ($i=0;$i<strlen($txt);$i++){
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
function RandPass()
{
$randomPassword = "";
srand((double)microtime()*1000000);
for($i=0;$i<8;$i++)
{
$randnumber = rand(48,120);
while (($randnumber >= 58 && $randnumber <= 64) || ($randnumber >= 91 && $randnumber <= 96))
{
$randnumber = rand(48,120);
}
$randomPassword .= chr($randnumber);
}
return $randomPassword;
}
}
?>
@@ -0,0 +1,92 @@
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_access extends ADODB_DataDict {
var $databaseType = 'access';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'TEXT';
case 'XL':
case 'X': return 'MEMO';
case 'C2': return 'TEXT'; /* up to 32K */
case 'X2': return 'MEMO';
case 'B': return 'BINARY';
case 'D': return 'DATETIME';
case 'T': return 'DATETIME';
case 'L': return 'BYTE';
case 'I': return 'INTEGER';
case 'I1': return 'BYTE';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'INTEGER';
case 'F': return 'DOUBLE';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
/* return string must begin with space */
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'COUNTER';
return '';
}
if (substr($ftype,0,7) == 'DECIMAL') $ftype = 'DECIMAL';
$suffix = '';
if (strlen($fdefault)) {
/* $suffix .= " DEFAULT $fdefault"; */
if ($this->debug) ADOConnection::outp("Warning: Access does not supported DEFAULT values (field $fname)");
}
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function CreateDatabase($dbname,$options=false)
{
return array();
}
function SetSchema($schema)
{
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
return array();
}
}
?>
+74
View File
@@ -0,0 +1,74 @@
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_db2 extends ADODB_DataDict {
var $databaseType = 'db2';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'VARCHAR(3600)';
case 'C2': return 'VARCHAR'; /* up to 32K */
case 'X2': return 'VARCHAR(3600)'; /* up to 32000, but default page size too small */
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
/* return string must begin with space */
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if ($fautoinc) return ' GENERATED ALWAYS AS IDENTITY'; # as identity start with
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
return array();
}
}
?>
+122
View File
@@ -0,0 +1,122 @@
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_generic extends ADODB_DataDict {
var $databaseType = 'generic';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'VARCHAR(250)';
case 'C2': return 'VARCHAR';
case 'X2': return 'VARCHAR(250)';
case 'B': return 'VARCHAR';
case 'D': return 'DATE';
case 'T': return 'DATE';
case 'L': return 'DECIMAL(1)';
case 'I': return 'DECIMAL(10)';
case 'I1': return 'DECIMAL(3)';
case 'I2': return 'DECIMAL(5)';
case 'I4': return 'DECIMAL(10)';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'DECIMAL(32,8)';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
return array();
}
}
/*
//db2
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'X': return 'VARCHAR';
case 'C2': return 'VARCHAR'; // up to 32K
case 'X2': return 'VARCHAR';
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
// ifx
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';// 255
case 'X': return 'TEXT';
case 'C2': return 'NVARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'DATETIME';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'FLOAT';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
*/
?>
+64
View File
@@ -0,0 +1,64 @@
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_ibase extends ADODB_DataDict {
var $databaseType = 'ibase';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'VARCHAR(4000)';
case 'C2': return 'VARCHAR'; /* up to 32K */
case 'X2': return 'VARCHAR(4000)';
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'INTEGER';
case 'F': return 'DOUBLE PRECISION';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
return array();
}
}
?>
@@ -0,0 +1,77 @@
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_informix extends ADODB_DataDict {
var $databaseType = 'informix';
var $seqField = false;
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';/* 255 */
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'NVARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BLOB';
case 'D': return 'DATE';
case 'T': return 'DATETIME';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INTEGER';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'FLOAT';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported");
return array();
}
/* return string must begin with space */
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
}
?>
+210 -182
View File
@@ -1,183 +1,211 @@
<?php
/**
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_mssql extends ADODB_DataDict {
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'X': return 'TEXT';
case 'C2': return 'NVARCHAR';
case 'X2': return 'NTEXT';
case 'B': return 'IMAGE';
case 'D': return 'DATETIME';
case 'T': return 'DATETIME';
case 'L': return 'BIT';
case 'I': return 'INT';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INT';
case 'I8': return 'BIGINT';
case 'F': return 'REAL';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname $this->addCol";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f);
$sql[] = $s;
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
if (!is_array($flds)) $flds = explode(',',$flds);
$f = array();
$s = "ALTER TABLE $tabname";
foreach($flds as $v) {
$f[] = "\n$this->dropCol $v";
}
$s .= implode(',',$f);
$sql[] = $s;
return $sql;
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }
| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)
[ ON { filegroup | DEFAULT } ]
[ TEXTIMAGE_ON { filegroup | DEFAULT } ]
< column_definition > ::= { column_name data_type }
[ COLLATE < collation_name > ]
[ [ DEFAULT constant_expression ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL]
[ < column_constraint > ] [ ...n ]
< column_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[ WITH FILLFACTOR = fillfactor ]
[ON {filegroup | DEFAULT} ] ]
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
]
| CHECK [ NOT FOR REPLICATION ]
( logical_expression )
}
< table_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
{ ( column [ ASC | DESC ] [ ,...n ] ) }
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ]
( search_conditions )
}
*/
/*
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
[ WITH < index_option > [ ,...n] ]
[ ON filegroup ]
< index_option > :: =
{ PAD_INDEX |
FILLFACTOR = fillfactor |
IGNORE_DUP_KEY |
DROP_EXISTING |
STATISTICS_NORECOMPUTE |
SORT_IN_TEMPDB
}
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
if (isset($idxoptions['CLUSTERED'])) $clustered = ' CLUSTERED';
else $clustered = '';
$s = "CREATE$unique$clustered INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_mssql extends ADODB_DataDict {
var $databaseType = 'mssql';
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; /* mysql max_length is not accurate */
switch (strtoupper($t)) {
case 'INT':
case 'INTEGER': return 'I';
case 'BIT':
case 'TINYINT': return 'I1';
case 'SMALLINT': return 'I2';
case 'BIGINT': return 'I8';
case 'REAL':
case 'FLOAT': return 'F';
default: return parent::MetaType($t,$len,$fieldobj);
}
}
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'NVARCHAR';
case 'X2': return 'NTEXT';
case 'B': return 'IMAGE';
case 'D': return 'DATETIME';
case 'T': return 'DATETIME';
case 'L': return 'BIT';
case 'I': return 'INT';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'INT';
case 'I8': return 'BIGINT';
case 'F': return 'REAL';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AddColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname $this->addCol";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f);
$sql[] = $s;
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
$sql = array();
list($lines,$pkey) = $this->_GenFields($flds);
foreach($lines as $v) {
$sql[] = "ALTER TABLE $tabname $this->alterCol $v";
}
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->schema) $tabname = $this->schema.'.'.$tabname;
if (!is_array($flds)) $flds = explode(',',$flds);
$f = array();
$s = "ALTER TABLE $tabname";
foreach($flds as $v) {
$f[] = "\n$this->dropCol $v";
}
$s .= implode(',',$f);
$sql[] = $s;
return $sql;
}
/* return string must begin with space */
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' IDENTITY(1,1)';
if ($fnotnull) $suffix .= ' NOT NULL';
else if ($suffix == '') $suffix .= ' NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE TABLE
[ database_name.[ owner ] . | owner. ] table_name
( { < column_definition >
| column_name AS computed_column_expression
| < table_constraint > ::= [ CONSTRAINT constraint_name ] }
| [ { PRIMARY KEY | UNIQUE } [ ,...n ]
)
[ ON { filegroup | DEFAULT } ]
[ TEXTIMAGE_ON { filegroup | DEFAULT } ]
< column_definition > ::= { column_name data_type }
[ COLLATE < collation_name > ]
[ [ DEFAULT constant_expression ]
| [ IDENTITY [ ( seed , increment ) [ NOT FOR REPLICATION ] ] ]
]
[ ROWGUIDCOL]
[ < column_constraint > ] [ ...n ]
< column_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
[ WITH FILLFACTOR = fillfactor ]
[ON {filegroup | DEFAULT} ] ]
]
| [ [ FOREIGN KEY ]
REFERENCES ref_table [ ( ref_column ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
]
| CHECK [ NOT FOR REPLICATION ]
( logical_expression )
}
< table_constraint > ::= [ CONSTRAINT constraint_name ]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED ]
{ ( column [ ASC | DESC ] [ ,...n ] ) }
[ WITH FILLFACTOR = fillfactor ]
[ ON { filegroup | DEFAULT } ]
]
| FOREIGN KEY
[ ( column [ ,...n ] ) ]
REFERENCES ref_table [ ( ref_column [ ,...n ] ) ]
[ ON DELETE { CASCADE | NO ACTION } ]
[ ON UPDATE { CASCADE | NO ACTION } ]
[ NOT FOR REPLICATION ]
| CHECK [ NOT FOR REPLICATION ]
( search_conditions )
}
*/
/*
CREATE [ UNIQUE ] [ CLUSTERED | NONCLUSTERED ] INDEX index_name
ON { table | view } ( column [ ASC | DESC ] [ ,...n ] )
[ WITH < index_option > [ ,...n] ]
[ ON filegroup ]
< index_option > :: =
{ PAD_INDEX |
FILLFACTOR = fillfactor |
IGNORE_DUP_KEY |
DROP_EXISTING |
STATISTICS_NORECOMPUTE |
SORT_IN_TEMPDB
}
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
if (isset($idxoptions['CLUSTERED'])) $clustered = ' CLUSTERED';
else $clustered = '';
$s = "CREATE$unique$clustered INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
?>
+146 -91
View File
@@ -1,92 +1,147 @@
<?php
/**
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_mysql extends ADODB_DataDict {
var $alterCol = ' MODIFY COLUMN';
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'X': return 'LONGTEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'LONGTEXT';
case 'B': return 'LONGBLOB';
case 'D': return 'DATE';
case 'T': return 'DATETIME';
case 'L': return 'TINYINT';
case 'I': return 'INTEGER';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'MEDIUMINT';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if ($fnotnull) $suffix .= ' NOT NULL';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]
create_definition:
col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
[PRIMARY KEY] [reference_definition]
or PRIMARY KEY (index_col_name,...)
or KEY [index_name] (index_col_name,...)
or INDEX [index_name] (index_col_name,...)
or UNIQUE [INDEX] [index_name] (index_col_name,...)
or FULLTEXT [INDEX] [index_name] (index_col_name,...)
or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
[reference_definition]
or CHECK (expr)
*/
/*
CREATE [UNIQUE|FULLTEXT] INDEX index_name
ON tbl_name (col_name[(length)],... )
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
//if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX IF EXISTS $idxname";
if (isset($idxoptions['FULLTEXT'])) $unique = ' FULLTEXT';
else if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_mysql extends ADODB_DataDict {
var $databaseType = 'mysql';
var $alterCol = ' MODIFY COLUMN';
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; /* mysql max_length is not accurate */
switch (strtoupper($t)) {
case 'STRING':
case 'CHAR':
case 'VARCHAR':
case 'TINYBLOB':
case 'TINYTEXT':
case 'ENUM':
case 'SET':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
case 'LONGTEXT':
case 'MEDIUMTEXT':
return 'X';
/* php_mysql extension always returns 'blob' even if 'text' */
/* so we have to check whether binary... */
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'YEAR':
case 'DATE': return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP': return 'T';
case 'FLOAT':
case 'DOUBLE':
return 'F';
case 'INT':
case 'INTEGER': return (!empty($fieldobj->primary_key)) ? 'R' : 'I';
case 'TINYINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I1';
case 'SMALLINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I2';
case 'MEDIUMINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I4';
case 'BIGINT': return (!empty($fieldobj->primary_key)) ? 'R' : 'I8';
default: return 'N';
}
}
function ActualType($meta)
{
switch(strtoupper($meta)) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'LONGTEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'LONGTEXT';
case 'B': return 'LONGBLOB';
case 'D': return 'DATE';
case 'T': return 'DATETIME';
case 'L': return 'TINYINT';
case 'I': return 'INTEGER';
case 'I1': return 'TINYINT';
case 'I2': return 'SMALLINT';
case 'I4': return 'MEDIUMINT';
case 'I8': return 'BIGINT';
case 'F': return 'DOUBLE';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
/* return string must begin with space */
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($funsigned) $suffix .= ' UNSIGNED';
if ($fnotnull) $suffix .= ' NOT NULL';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fautoinc) $suffix .= ' AUTO_INCREMENT';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]
create_definition:
col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
[PRIMARY KEY] [reference_definition]
or PRIMARY KEY (index_col_name,...)
or KEY [index_name] (index_col_name,...)
or INDEX [index_name] (index_col_name,...)
or UNIQUE [INDEX] [index_name] (index_col_name,...)
or FULLTEXT [INDEX] [index_name] (index_col_name,...)
or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
[reference_definition]
or CHECK (expr)
*/
/*
CREATE [UNIQUE|FULLTEXT] INDEX index_name
ON tbl_name (col_name[(length)],... )
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
/* if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX IF EXISTS $idxname"; */
if (isset($idxoptions['FULLTEXT'])) $unique = ' FULLTEXT';
else if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
?>
+243 -179
View File
@@ -1,180 +1,244 @@
<?php
/**
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_oci8 extends ADODB_DataDict {
var $seqField = false;
var $seqPrefix = 'SEQ_';
var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'X': return 'CLOB';
case 'C2': return 'NVARCHAR';
case 'X2': return 'NCLOB';
case 'B': return 'BLOB';
case 'D':
case 'T': return 'DATE';
case 'L': return 'NUMBER(1)';
case 'I1': return 'NUMBER(3)';
case 'I2': return 'NUMBER(5)';
case 'I':
case 'I4': return 'NUMBER(10)';
case 'I8': return 'NUMBER(20)';
case 'F': return 'NUMBER';
case 'N': return 'NUMBER';
default:
return $meta;
}
}
function CreateDatabase($dbname, $options=false)
{
$options = $this->_Options($options);
$password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';
$tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';
$sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;
$sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";
return $sql;
}
function AddColumnSQL($tabname, $flds)
{
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname ADD (";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$sql[] = $s;
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname MODIFY(";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$sql[] = $s;
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for Oracle");
return array();
}
// return string must begin with space
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint)
{
$suffix = '';
if ($fdefault == "''" && $fnotnull) {// this is null in oracle
$fnotnull = false;
if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");
}
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) {
$suffix .= ' NOT NULL';
}
if ($fautoinc) $this->seqField = $fname;
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE or replace TRIGGER jaddress_insert
before insert on jaddress
for each row
begin
select seqaddress.nextval into :new.A_ID from dual;
end;
*/
function _Triggers($tabname,$tableoptions)
{
if (!$this->seqField) return array();
if ($this->schema) {
$t = strpos($tabname,'.');
if ($t !== false) $tab = substr($tabname,$t+1);
else $tab = $tabname;
$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
$trigname = $this->schema.'.TRIG_'.$this->seqPrefix.$tab;
} else {
$seqname = $this->seqPrefix.$tabname;
$trigname = "TRIG_$seqname";
}
if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
$sql[] = "CREATE SEQUENCE $seqname";
$sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname
FOR EACH ROW
BEGIN
select $seqname.nextval into :new.$this->seqField from dual;
END";
$this->seqField = false;
return $sql;
}
/*
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]
create_definition:
col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
[PRIMARY KEY] [reference_definition]
or PRIMARY KEY (index_col_name,...)
or KEY [index_name] (index_col_name,...)
or INDEX [index_name] (index_col_name,...)
or UNIQUE [INDEX] [index_name] (index_col_name,...)
or FULLTEXT [INDEX] [index_name] (index_col_name,...)
or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
[reference_definition]
or CHECK (expr)
*/
function _IndexSQL($idxname, $tabname, $flds,$idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['BITMAP'])) {
$unique = ' BITMAP';
} else if (isset($idxoptions['UNIQUE']))
$unique = ' UNIQUE';
else
$unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$sql[] = $s;
return $sql;
}
}
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_oci8 extends ADODB_DataDict {
var $databaseType = 'oci8';
var $seqField = false;
var $seqPrefix = 'SEQ_';
var $dropTable = "DROP TABLE %s CASCADE CONSTRAINTS";
function MetaType($t,$len=-1)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'VARCHAR':
case 'VARCHAR2':
case 'CHAR':
case 'VARBINARY':
case 'BINARY':
if (isset($this) && $len <= $this->blobSize) return 'C';
return 'X';
case 'NCHAR':
case 'NVARCHAR2':
case 'NVARCHAR':
if (isset($this) && $len <= $this->blobSize) return 'C2';
return 'X2';
case 'NCLOB':
case 'CLOB';
return 'XL';
case 'LONG RAW':
case 'LONG VARBINARY':
case 'BLOB':
return 'B';
case 'DATE':
return 'T';
case 'INT':
case 'SMALLINT':
case 'INTEGER':
return 'I';
default:
return 'N';
}
}
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'X': return 'VARCHAR(4000)';
case 'XL': return 'CLOB';
case 'C2': return 'NVARCHAR';
case 'X2': return 'NVARCHAR(2000)';
case 'B': return 'BLOB';
case 'D':
case 'T': return 'DATE';
case 'L': return 'DECIMAL(1)';
case 'I1': return 'DECIMAL(3)';
case 'I2': return 'DECIMAL(5)';
case 'I':
case 'I4': return 'DECIMAL(10)';
case 'I8': return 'DECIMAL(20)';
case 'F': return 'DECIMAL';
case 'N': return 'DECIMAL';
default:
return $meta;
}
}
function CreateDatabase($dbname, $options=false)
{
$options = $this->_Options($options);
$password = isset($options['PASSWORD']) ? $options['PASSWORD'] : 'tiger';
$tablespace = isset($options["TABLESPACE"]) ? " DEFAULT TABLESPACE ".$options["TABLESPACE"] : '';
$sql[] = "CREATE USER ".$dbname." IDENTIFIED BY ".$password.$tablespace;
$sql[] = "GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO $dbname";
return $sql;
}
function AddColumnSQL($tabname, $flds)
{
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname ADD (";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$sql[] = $s;
return $sql;
}
function AlterColumnSQL($tabname, $flds)
{
$f = array();
list($lines,$pkey) = $this->_GenFields($flds);
$s = "ALTER TABLE $tabname MODIFY(";
foreach($lines as $v) {
$f[] = "\n $v";
}
$s .= implode(',',$f).')';
$sql[] = $s;
return $sql;
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for Oracle");
return array();
}
function _DropAutoIncrement($t)
{
return "drop sequence seq_".$t;
}
/* return string must begin with space */
function _CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
{
$suffix = '';
if ($fdefault == "''" && $fnotnull) {/* this is null in oracle */
$fnotnull = false;
if ($this->debug) ADOConnection::outp("NOT NULL and DEFAULT='' illegal in Oracle");
}
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fautoinc) $this->seqField = $fname;
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE or replace TRIGGER jaddress_insert
before insert on jaddress
for each row
begin
select seqaddress.nextval into :new.A_ID from dual;
end;
*/
function _Triggers($tabname,$tableoptions)
{
if (!$this->seqField) return array();
if ($this->schema) {
$t = strpos($tabname,'.');
if ($t !== false) $tab = substr($tabname,$t+1);
else $tab = $tabname;
$seqname = $this->schema.'.'.$this->seqPrefix.$tab;
$trigname = $this->schema.'.TRIG_'.$this->seqPrefix.$tab;
} else {
$seqname = $this->seqPrefix.$tabname;
$trigname = "TRIG_$seqname";
}
if (isset($tableoptions['REPLACE'])) $sql[] = "DROP SEQUENCE $seqname";
$sql[] = "CREATE SEQUENCE $seqname";
$sql[] = "CREATE OR REPLACE TRIGGER $trigname BEFORE insert ON $tabname
FOR EACH ROW
BEGIN
select $seqname.nextval into :new.$this->seqField from dual;
END;";
$this->seqField = false;
return $sql;
}
/*
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)]
[table_options] [select_statement]
create_definition:
col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT]
[PRIMARY KEY] [reference_definition]
or PRIMARY KEY (index_col_name,...)
or KEY [index_name] (index_col_name,...)
or INDEX [index_name] (index_col_name,...)
or UNIQUE [INDEX] [index_name] (index_col_name,...)
or FULLTEXT [INDEX] [index_name] (index_col_name,...)
or [CONSTRAINT symbol] FOREIGN KEY [index_name] (index_col_name,...)
[reference_definition]
or CHECK (expr)
*/
function _IndexSQL($idxname, $tabname, $flds,$idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['BITMAP'])) {
$unique = ' BITMAP';
} else if (isset($idxoptions['UNIQUE']))
$unique = ' UNIQUE';
else
$unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ($flds)";
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
if (isset($idxoptions['oci8'])) $s .= $idxoptions['oci8'];
$sql[] = $s;
return $sql;
}
function GetCommentSQL($table,$col)
{
$table = $this->connection->qstr($table);
$col = $this->connection->qstr($col);
return "select comments from USER_COL_COMMENTS where TABLE_NAME=$table and COLUMN_NAME=$col";
}
function SetCommentSQL($table,$col,$cmt)
{
$cmt = $this->connection->qstr($cmt);
return "COMMENT ON COLUMN $table.$col IS $cmt";
}
}
?>
+190 -122
View File
@@ -1,123 +1,191 @@
<?php
/**
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_postgres extends ADODB_DataDict {
var $seqField = false;
var $seqPrefix = 'SEQ_';
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BYTEA';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
case 'I4': return 'INT4';
case 'I8': return 'INT8';
case 'F': return 'FLOAT8';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for PostgreSQL");
return array();
}
// return string must begin with space
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
/*
CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
{ column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
| table_constraint } [, ... ]
)
[ INHERITS ( parent_table [, ... ] ) ]
[ WITH OIDS | WITHOUT OIDS ]
where column_constraint is:
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | UNIQUE | PRIMARY KEY |
CHECK (expression) |
REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
[ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
and table_constraint is:
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ... ] ) |
PRIMARY KEY ( column_name [, ... ] ) |
CHECK ( expression ) |
FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
[ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
*/
/*
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_method ] ( column [ ops_name ] [, ...] )
[ WHERE predicate ]
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
[ WHERE predicate ]
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ";
if (isset($idxoptions['HASH'])) $s .= 'USING HASH ';
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$s .= "($flds)";
$sql[] = $s;
return $sql;
}
}
<?php
/**
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
class ADODB2_postgres extends ADODB_DataDict {
var $databaseType = 'postgres';
var $seqField = false;
var $seqPrefix = 'SEQ_';
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'INTERVAL':
case 'CHAR':
case 'CHARACTER':
case 'VARCHAR':
case 'NAME':
case 'BPCHAR':
if ($len <= $this->blobSize) return 'C';
case 'TEXT':
return 'X';
case 'IMAGE': /* user defined type */
case 'BLOB': /* user defined type */
case 'BIT': /* This is a bit string, not a single bit, so don't return 'L' */
case 'VARBIT':
case 'BYTEA':
return 'B';
case 'BOOL':
case 'BOOLEAN':
return 'L';
case 'DATE':
return 'D';
case 'TIME':
case 'DATETIME':
case 'TIMESTAMP':
case 'TIMESTAMPTZ':
return 'T';
case 'INTEGER': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I' : 'R';
case 'SMALLINT':
case 'INT2': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I2' : 'R';
case 'INT4': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I4' : 'R';
case 'BIGINT':
case 'INT8': return (empty($fieldobj->primary_key) && empty($fieldobj->unique))? 'I8' : 'R';
case 'OID':
case 'SERIAL':
return 'R';
case 'FLOAT4':
case 'FLOAT8':
case 'DOUBLE PRECISION':
case 'REAL':
return 'F';
default:
return 'N';
}
}
function ActualType($meta)
{
switch($meta) {
case 'C': return 'VARCHAR';
case 'XL':
case 'X': return 'TEXT';
case 'C2': return 'VARCHAR';
case 'X2': return 'TEXT';
case 'B': return 'BYTEA';
case 'D': return 'DATE';
case 'T': return 'TIMESTAMP';
case 'L': return 'SMALLINT';
case 'I': return 'INTEGER';
case 'I1': return 'SMALLINT';
case 'I2': return 'INT2';
case 'I4': return 'INT4';
case 'I8': return 'INT8';
case 'F': return 'FLOAT8';
case 'N': return 'NUMERIC';
default:
return $meta;
}
}
function AlterColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported for PostgreSQL");
return array();
}
function DropColumnSQL($tabname, $flds)
{
if ($this->debug) ADOConnection::outp("DropColumnSQL not supported for PostgreSQL");
return array();
}
/* return string must begin with space */
function _CreateSuffix($fname, &$ftype, $fnotnull,$fdefault,$fautoinc,$fconstraint)
{
if ($fautoinc) {
$ftype = 'SERIAL';
return '';
}
$suffix = '';
if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
if ($fnotnull) $suffix .= ' NOT NULL';
if ($fconstraint) $suffix .= ' '.$fconstraint;
return $suffix;
}
function _DropAutoIncrement($t)
{
return "drop sequence ".$t."_m_id_seq";
}
/*
CREATE [ [ LOCAL ] { TEMPORARY | TEMP } ] TABLE table_name (
{ column_name data_type [ DEFAULT default_expr ] [ column_constraint [, ... ] ]
| table_constraint } [, ... ]
)
[ INHERITS ( parent_table [, ... ] ) ]
[ WITH OIDS | WITHOUT OIDS ]
where column_constraint is:
[ CONSTRAINT constraint_name ]
{ NOT NULL | NULL | UNIQUE | PRIMARY KEY |
CHECK (expression) |
REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL ]
[ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
and table_constraint is:
[ CONSTRAINT constraint_name ]
{ UNIQUE ( column_name [, ... ] ) |
PRIMARY KEY ( column_name [, ... ] ) |
CHECK ( expression ) |
FOREIGN KEY ( column_name [, ... ] ) REFERENCES reftable [ ( refcolumn [, ... ] ) ]
[ MATCH FULL | MATCH PARTIAL ] [ ON DELETE action ] [ ON UPDATE action ] }
[ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
*/
/*
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_method ] ( column [ ops_name ] [, ...] )
[ WHERE predicate ]
CREATE [ UNIQUE ] INDEX index_name ON table
[ USING acc_method ] ( func_name( column [, ... ]) [ ops_name ] )
[ WHERE predicate ]
*/
function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
{
if (isset($idxoptions['REPLACE'])) $sql[] = "DROP INDEX $idxname";
if (isset($idxoptions['UNIQUE'])) $unique = ' UNIQUE';
else $unique = '';
if (is_array($flds)) $flds = implode(', ',$flds);
$s = "CREATE$unique INDEX $idxname ON $tabname ";
if (isset($idxoptions['HASH'])) $s .= 'USING HASH ';
if (isset($idxoptions[$this->upperName])) $s .= $idxoptions[$this->upperName];
$s .= "($flds)";
$sql[] = $s;
return $sql;
}
}
?>
File diff suppressed because it is too large Load Diff
+293
View File
@@ -0,0 +1,293 @@
<html>
<head>
<title>ADODB Data Dictionary Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<XSTYLE
body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}
pre {font-size:9pt}
.toplink {font-size:8pt}
/>
</head>
<body bgcolor="#FFFFFF">
<h2>ADOdb Data Dictionary Library for PHP</h2>
<p> V3.60 16 June 2003 (c) 2000-2003 John Lim (<a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>)</p>
<p><font size=1>This software is dual licensed using BSD-Style and LGPL.
Where there is any discrepancy, the BSD-Style license will take precedence.
This means you can use it in proprietary and commercial products.</font></p>
<p>This documentation describes a class library to automate the creation of tables,
indexes and foreign key constraints portably for multiple databases. Download
from <a href="http://php.weblogs.com/adodb">http://php.weblogs.com/adodb</a>
<p>Currently the following databases are supported:
<p> Well-tested: PostgreSQL, MySQL, Oracle, MSSQL. <br>
Beta-quality: DB2, Informix, Sybase, Interbase, Firebird.<br>
Alpha-quality: MS Access (does not support DEFAULT values) and generic ODBC.</p>
<h3>Example Usage</h3>
<pre>include_once('adodb.inc.php');
<font color="#006600">
# First create a normal connection
</font>$db->NewADOConnection('mysql');
$db->Connect(...);
<br>
<font color="#006600"># Then create a data dictionary object, using this connection
</font>$dict = <strong>NewDataDictionary</strong>($db);
<font color="#006600"># We have a portable declarative data dictionary format in ADOdb 3.50, similar to SQL.
# Field types use 1 character codes, and fields are separated by commas.
# The following example creates three fields: "col1", "col2" and "col3":</font>
$flds = "
<font color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',
col2 I DEFAULT 0,
col3 N(12.2)</strong></font>
";<br>
<font color="#006600"># We demonstrate creating tables and indexes</font>
$sqlarray = $dict-><strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);
$dict-><strong>ExecuteSQLArray</strong>($sqlarray);<br>
$idxflds = 'co11, col2';
$sqlarray = $dict-><strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);
$dict-><strong>ExecuteSQLArray</strong>($sqlarray);
</pre>
<h3>Functions</h3>
<p><b>function CreateDatabase($dbname, $optionsarray=false)</b>
<p>Create a database with the name $dbname;
<p><b>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</b>
<pre>
RETURNS: an array of strings, the sql to be executed, or false
$tabname: name of table
$fldarray: string (or array) containing field info
$taboptarray: array containing table options
</pre>
<p>
The new format of $fldarray uses a free text format, where each field is comma-delimited.
The first token for each field is the field name, followed by the type and optional
field size. Then optional keywords in $otheroptions:
<pre> "$fieldname $type $colsize $otheroptions"</pre>
<p> The older (and still supported) format of $fldarray is a 2-dimensional array, where each row in the
1st dimension represents one field. Each row has this format:
<pre> array($fieldname, $type, [,$colsize] [,$otheroptions]*)</pre>
The first 2 fields must be the field name and the field type. The field type
can be a portable type codes or the actual type for that database.
<p>
Legal portable type codes include:
<pre>
C: varchar
X: Largest varchar size
XL: For Oracle, returns CLOB, otherwise same as 'X' above
C2: Multibyte varchar
X2: Multibyte varchar (largest size)
B: BLOB (binary large object)<br>
D: Date (some databases do not support this, and we return a datetime type)
T: Datetime or Timestamp
L: Integer field suitable for storing booleans (0 or 1)
I: Integer (mapped to I4)
I1: 1-byte integer
I2: 2-byte integer
I4: 4-byte integer
I8: 8-byte integer
F: Floating point number
N: Numeric or decimal number
</pre>
<p> The $colsize field represents the size of the field. If a decimal number is
used, then it is assumed that the number following the dot is the precision,
so 6.2 means a number of size 6 digits and 2 decimal places. It is
recommended that the default for number types be represented as a string to
avoid any rounding errors.
<p>
The $otheroptions include the following keywords (case-insensitive):
<pre>
AUTO For autoincrement number. Emulated with triggers if not available.
Sets NOTNULL also.
AUTOINCREMENT Same as auto.
KEY Primary key field. Sets NOTNULL also. Compound keys are supported.
PRIMARY Same as KEY.
DEF Synonym for DEFAULT for lazy typists.
DEFAULT The default value. Character strings are auto-quoted unless
the string begins and ends with spaces, eg ' SYSDATE '.
NOTNULL If field is not null.
DEFDATE Set default value to call function to get today's date.
DEFTIMESTAMP Set default to call function to get today's datetime.
NOQUOTE Prevents autoquoting of default string values.
CONSTRAINTS Additional constraints defined at the end of the field
definition.
</pre>
<p> The Data Dictonary accepts two formats, the older array specification: </p>
<pre>
$flds = array(
array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' => 0, 'NotNull'),
array('ID', 'I' , 'AUTO'),
array('MYDATE', 'D' , 'DEFDATE'),
array('NAME', 'C' ,'32',
'CONSTRAINTS' => 'FOREIGN KEY REFERENCES reftable')
); </pre>
Or the simpler declarative format:
<pre> $flds = "
<font color="#660000"><strong> COLNAME DECIMAL(8.4) DEFAULT 0 NotNull,
ID I AUTO,
MYDATE D DEFDATE,
NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable' </strong></font>
";
</pre>
<p>
The $taboptarray is the 3rd parameter of the CreateTableSQL function.
This contains table specific settings. Legal keywords include:
<ul>
<li>REPLACE <br>
Indicates that the previous table definition should be removed (dropped)together
with ALL data. See first example below.<br>
</li>
<li>CONSTRAINTS <br>
Define this as the key, with the constraint as the value. See the postgresql
example below. Additional constraints defined for the whole table. You
will probably need to prefix this with a comma. </li>
</ul>
<p> Database specific table options can be defined also using the name of the
database type as the array key. In the following example, <em>create the table
as ISAM with MySQL, and store the table in the &quot;users&quot; tablespace
if using Oracle</em>. And if the table already exists, drop the table first.
<pre> $taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users', 'REPLACE'); </pre>
<p>
You can also define foreignkey constraints. The following is syntax for
postgresql:<pre>
$taboptarray = array('constraints' =>
', FOREIGN KEY (col1) REFERENCES reftable (refcol)');
</pre>
<p><strong>function ChangeTableSQL($tabname, $flds)</strong>
<p>Checks to see if table exists, if table does not exist, behaves like CreateTableSQL.
If table exists, generates appropriate ALTER TABLE MODIFY COLUMN commands if
field already exists, or ALTER TABLE ADD $column if field does not exist.
<p>The class must be connected to the database for ChangeTableSQL to detect the
existance of the table. Idea and code contributed by Florian Buzin.
<p><b>function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)</b>
<p>
RETURNS: an array of strings, the sql to be executed, or false
<pre>
$idxname: name of index
$tabname: name of table
$flds: list of fields as a comma delimited string or an array of strings
$idxoptarray: array of index creation options
</pre>
<p> $idxoptarray is similar to $taboptarray in that index specific information can
be embedded in the array. Other options include:
<pre>
CLUSTERED Create clustered index (only mssql)
BITMAP Create bitmap index (only oci8)
UNIQUE Make unique index
FULLTEXT Make fulltext index (only mysql)
HASH Create hash index (only postgres)
</pre>
<p> <strong>function AddColumnSQL($tabname, $flds)</strong>
<p>Add one or more columns. Not guaranteed to work under all situations.
<p><strong>function AlterColumnSQL($tabname, $flds)</strong>
<p>Warning, not all databases support this feature.
<p> <strong>function DropColumnSQL($tabname, $flds)</strong>
<p>Drop 1 or more columns.
<p> <strong>function ExecuteSQLArray($sqlarray, $contOnError = true)</strong>
<pre>
RETURNS: 0 if failed, 1 if executed all but with errors, 2 if executed successfully
$sqlarray: an array of strings with sql code (no semicolon at the end of string)
$contOnError: if true, then continue executing even if error occurs
</pre>
<p>Executes an array of SQL strings returned by CreateTableSQL or CreateIndexSQL.
<hr><a name=xmlschema></a>
<h2>XML Schema</h2>
This is a class contributed by Richard Tango-Lowy that allows the user to quickly
and easily build a database using the excellent
ADODB database library and a simple XML formatted file.
<H3>Quick Start</H3>
<P>First, create an XML database schema. Let's call it "schema.xml:"</P><PRE>
&lt;?xml version="1.0"?&gt;
&lt;schema&gt;
&lt;table name="mytable"&gt;
&lt;field name="row1" type="I"&gt;
&lt;descr&gt;An integer row that's a primary key and autoincrements&lt;/descr&gt;
&lt;KEY/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;/field&gt;
&lt;field name="row2" type="C" size="16"&gt;
&lt;descr&gt;A 16 character varchar row that can't be null&lt;/descr&gt;
&lt;NOTNULL/&gt;
&lt;/field&gt;
&lt;/table&gt;
&lt;index name="myindex" table="mytable"&gt;
&lt;col&gt;row1&lt;/col&gt;
&lt;col&gt;row2&lt;/col&gt;
&lt;/index&gt;
&lt;sql&gt;
&lt;descr&gt;SQL to be executed only on specific platforms&lt;/descr&gt;
&lt;query platform="postgres|postgres7"&gt;
insert into mytable ( row1, row2 ) values ( 12, 'stuff' )
&lt;/query&gt;
&lt;query platform="mysql"&gt;
insert into mytable ( row1, row2 ) values ( 12, 'different stuff' )
&lt;/query&gt;
&lt;/sql&gt;
&lt;/schema&gt;
</PRE><P>Create a new database using the appropriate tool for your platform.
Executing the following PHP code will create the a <i>mytable</i> and <i>myindex</i>
in the database and insert one row into <i>mytable</i> if the platform is postgres or mysql. </P><PRE>
include_once('/path/to/adodb.inc.php');
include_once('/path/to/adodb-xmlschema.inc.php');
// To build the schema, start by creating a normal ADOdb connection:
$db->NewADOConnection( 'mysql' );
$db->Connect( ... );
// Create the schema object and build the query array.
$schema = <B>new adoSchema</B>( $db );
// Build the SQL array
$sql = $schema-><B>ParseSchema</B>( "schema.xml" );
// Execute the SQL on the database
$result = $schema-><B>ExecuteSchema</B>( $sql );
// Finally, clean up after the XML parser
// (PHP won't do this for you!)
$schema-><B>Destroy</B>();
</PRE>
<H3>XML Schema Format:</H3>
<P>(See <a href="http://arscognita.com/xmlschema.dtd">ADOdb_schema.dtd</a> for the full specification)</P>
<PRE>
&lt;?xml version="1.0"?&gt;
&lt;schema&gt;
&lt;table name="tablename" platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;field name="fieldname" type="datadict_type" size="size"&gt;
&lt;KEY/&gt;
&lt;NOTNULL/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;DEFAULT value="value"/&gt;
&lt;/field&gt;
... <i>more fields</i>
&lt;/table&gt;
... <i>more tables</i>
&lt;index name="indexname" platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;col&gt;fieldname&lt;/col&gt;
... <i>more columns</i>
&lt;/index&gt;
... <i>more indices</i>
&lt;sql platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;query platform="platform1|platform2|..."&gt;SQL query&lt;/query&gt;
... <i>more queries</i>
&lt;/sql&gt;
... <i>more SQL</i>
&lt;/schema&gt;
</PRE>
<HR>
<address>If you have any questions or comments, please email them to me at
<a href="mailto:richtl#arscognita.com">richtl#arscognita.com</a>.</address>
</body>
</html>
+130
View File
@@ -0,0 +1,130 @@
<html>
<head>
<title>ADODB Session Management Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<XSTYLE
body,td {font-family:Arial,Helvetica,sans-serif;font-size:11pt}
pre {font-size:9pt}
.toplink {font-size:8pt}
/>
</head>
<body bgcolor="#FFFFFF">
<h3>ADODB Session Management Manual</h3>
<p>
V3.60 16 June 2003 (c) 2000-2003 John Lim (jlim#natsoft.com.my)
<p>
<font size=1>This software is dual licensed using BSD-Style and LGPL. Where there is any discrepancy, the BSD-Style license will take precedence. This means you can use it in proprietary and commercial products.
</font>
<h3>Introduction</h3>
<p>PHP is packed with good features. One of the most popular is session variables.
These are variables that persist throughout a session, as the user moves from page to page. Session variables are great holders of state information and other useful stuff.
<p>
To use session variables, call session_start() at the beginning of your web page,
before your HTTP headers are sent. Then for every variable you want to keep alive
for the duration of the session, call session_register($variable_name). By default,
the session handler will keep track of the session by using a cookie. You can save objects
or arrays in session variables also.
<p>The default method of storing sessions is to store it in a file. However if you have multiple web servers,
or need to do special processing of each session, or require notification when a session expires, you
need to override the default session storage behaviour.
<p>The ADOdb session handler provides you with the above additional capabilities by storing
the session information as records in a database table that can be shared by multiple servers.
<h3>Setup</h3>
<p>There are 3 session management files that you can use:
<pre>
adodb-session.inc.php : The default
adodb-session-clob.inc.php : Use this if you are storing DATA in clobs
adodb-cryptsession.inc.php : Use this if you want to store encrypted session data in the database
<strong>Examples</strong>
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
To force non-persistent connections, call adodb_session_open first before session_start():
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session.php');
adodb_sess_open(false,false,false);
session_start();
session_register('AVAR');
$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</p>";
To use a encrypted sessions, simply replace the file:
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-cryptsession.php');
session_start();
And the same technique for adodb-session-clob.inc.php:
GLOBAL $HTTP_SESSION_VARS;
include('adodb.inc.php');
include('adodb-session-clob.php');
session_start();
<strong>Installation</strong>
1. Create this table in your database (syntax might vary depending on your db):
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
EXPIREREF varchar(64),
DATA text not null,
primary key (sesskey)
);
For the adodb-session-clob.inc.php version, create this:
create table sessions (
SESSKEY char(32) not null,
EXPIRY int(11) unsigned not null,
EXPIREREF varchar(64),
DATA CLOB,
primary key (sesskey)
);
2. Then define the following parameters in this file:
$ADODB_SESSION_DRIVER='database driver, eg. mysql or ibase';
$ADODB_SESSION_CONNECT='server to connect to';
$ADODB_SESSION_USER ='user';
$ADODB_SESSION_PWD ='password';
$ADODB_SESSION_DB ='database';
$ADODB_SESSION_TBL = 'sessions'
3. Recommended is PHP 4.0.6 or later. There are documented
session bugs in earlier versions of PHP.
4. If you want to receive notifications when a session expires, then
you can tag a session with an EXPIREREF, and before the session
record is deleted, we can call a function that will pass the EXPIREREF
as the first parameter, and the session key as the second parameter.
To do this, define a notification function, say NotifyFn:
function NotifyFn($expireref, $sesskey)
{
}
Then define a global variable, with the first parameter being the
global variable you would like to store in the EXPIREREF field, and
the second is the function name.
In this example, we want to be notified when a user's session
has expired, so we store the user id in $USERID, and make this
the value stored in the EXPIREREF field:
$ADODB_SESSION_EXPIRE_NOTIFY = array('USERID','NotifyFn');
</pre>
<p>
Also see the <a href=docs-adodb.htm>core ADOdb documentation</a>.
</body>
</html>
+73 -73
View File
@@ -1,74 +1,74 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Access data driver. Requires ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('_ADODB_ACCESS')) {
define('_ADODB_ACCESS',1);
class ADODB_access extends ADODB_odbc {
var $databaseType = 'access';
var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
var $fmtDate = "#Y-m-d#";
var $fmtTimeStamp = "#Y-m-d h:i:sA#"; // note not comma
var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
var $sysTimeStamp = 'NOW';
var $hasTransactions = false;
function ADODB_access()
{
global $ADODB_EXTENSION;
$ADODB_EXTENSION = false;
$this->ADODB_odbc();
}
function BeginTrans() { return false;}
function &MetaTables()
{
global $ADODB_FETCH_MODE;
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$qid = odbc_tables($this->_connectionID);
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr = &$rs->GetArray();
//print_pre($arr);
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')
$arr2[] = $arr[$i][2];
}
return $arr2;
}
}
class ADORecordSet_access extends ADORecordSet_odbc {
var $databaseType = "access";
function ADORecordSet_access($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}// class
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Access data driver. Requires ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('_ADODB_ACCESS')) {
define('_ADODB_ACCESS',1);
class ADODB_access extends ADODB_odbc {
var $databaseType = 'access';
var $hasTop = 'top'; /* support mssql SELECT TOP 10 * FROM TABLE */
var $fmtDate = "#Y-m-d#";
var $fmtTimeStamp = "#Y-m-d h:i:sA#"; /* note not comma */
var $_bindInputArray = false; /* strangely enough, setting to true does not work reliably */
var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
var $sysTimeStamp = 'NOW';
var $hasTransactions = false;
function ADODB_access()
{
global $ADODB_EXTENSION;
$ADODB_EXTENSION = false;
$this->ADODB_odbc();
}
function BeginTrans() { return false;}
function &MetaTables()
{
global $ADODB_FETCH_MODE;
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$qid = odbc_tables($this->_connectionID);
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
$arr = &$rs->GetArray();
/* print_pre($arr); */
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
if ($arr[$i][2] && $arr[$i][3] != 'SYSTEM TABLE')
$arr2[] = $arr[$i][2];
}
return $arr2;
}
}
class ADORecordSet_access extends ADORecordSet_odbc {
var $databaseType = "access";
function ADORecordSet_access($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}/* class */
}
?>
File diff suppressed because it is too large Load Diff
+45 -45
View File
@@ -1,46 +1,46 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
class ADODB_ado_access extends ADODB_ado {
var $databaseType = 'ado_access';
var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
var $fmtDate = "#Y-m-d#";
var $fmtTimeStamp = "#Y-m-d h:i:sA#";// note no comma
var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
var $sysTimeStamp = 'NOW';
var $hasTransactions = false;
function ADODB_ado_access()
{
$this->ADODB_ado();
}
function BeginTrans() { return false;}
}
class ADORecordSet_ado_access extends ADORecordSet_ado {
var $databaseType = "ado_access";
function ADORecordSet_ado_access($id,$mode=false)
{
return $this->ADORecordSet_ado($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence. See License.txt.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Access ADO data driver. Requires ADO and ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
class ADODB_ado_access extends ADODB_ado {
var $databaseType = 'ado_access';
var $hasTop = 'top'; /* support mssql SELECT TOP 10 * FROM TABLE */
var $fmtDate = "#Y-m-d#";
var $fmtTimeStamp = "#Y-m-d h:i:sA#";/* note no comma */
var $sysDate = "FORMAT(NOW,'yyyy-mm-dd')";
var $sysTimeStamp = 'NOW';
var $hasTransactions = false;
function ADODB_ado_access()
{
$this->ADODB_ado();
}
function BeginTrans() { return false;}
}
class ADORecordSet_ado_access extends ADORecordSet_ado {
var $databaseType = "ado_access";
function ADORecordSet_ado_access($id,$mode=false)
{
return $this->ADORecordSet_ado($id,$mode);
}
}
?>
+58 -58
View File
@@ -1,59 +1,59 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client.
Works only on MS Windows.
It is normally better to use the mssql driver directly because it is much faster.
This file is only a technology demonstration and for test purposes.
*/
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
class ADODB_ado_mssql extends ADODB_ado {
var $databaseType = 'ado_mssql';
var $hasTop = 'top';
var $sysDate = 'GetDate()';
var $sysTimeStamp = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; // for mssql7 or later
//var $_inTransaction = 1; // always open recordsets, so no transaction problems.
function ADODB_ado_mssql()
{
$this->ADODB_ado();
}
function _insertid()
{
return $this->GetOne('select @@identity');
}
function _affectedrows()
{
return $this->GetOne('select @@rowcount');
}
}
class ADORecordSet_ado_mssql extends ADORecordSet_ado {
var $databaseType = 'ado_mssql';
function ADORecordSet_ado_mssql($id,$mode=false)
{
return $this->ADORecordSet_ado($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft SQL Server ADO data driver. Requires ADO and MSSQL client.
Works only on MS Windows.
It is normally better to use the mssql driver directly because it is much faster.
This file is only a technology demonstration and for test purposes.
*/
if (!defined('_ADODB_ADO_LAYER')) {
include(ADODB_DIR."/drivers/adodb-ado.inc.php");
}
class ADODB_ado_mssql extends ADODB_ado {
var $databaseType = 'ado_mssql';
var $hasTop = 'top';
var $sysDate = 'GetDate()';
var $sysTimeStamp = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; /* for mssql7 or later */
/* var $_inTransaction = 1; // always open recordsets, so no transaction problems. */
function ADODB_ado_mssql()
{
$this->ADODB_ado();
}
function _insertid()
{
return $this->GetOne('select @@identity');
}
function _affectedrows()
{
return $this->GetOne('select @@rowcount');
}
}
class ADORecordSet_ado_mssql extends ADORecordSet_ado {
var $databaseType = 'ado_mssql';
function ADORecordSet_ado_mssql($id,$mode=false)
{
return $this->ADORecordSet_ado($id,$mode);
}
}
?>
+78 -78
View File
@@ -1,79 +1,79 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Support Borland Interbase 6.5 and later
*/
include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
class ADODB_borland_ibase extends ADODB_ibase {
var $databaseType = "borland_ibase";
function ADODB_borland_ibase()
{
$this->ADODB_ibase();
}
function ServerInfo()
{
$arr['dialect'] = $this->dialect;
switch($arr['dialect']) {
case '':
case '1': $s = 'Interbase 6.5, Dialect 1'; break;
case '2': $s = 'Interbase 6.5, Dialect 2'; break;
default:
case '3': $s = 'Interbase 6.5, Dialect 3'; break;
}
$arr['version'] = '6.5';
$arr['description'] = $s;
return $arr;
}
// Note that Interbase 6.5 uses ROWS instead - don't you love forking wars!
// SELECT col1, col2 FROM table ROWS 5 -- get 5 rows
// SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
// Firebird uses
// SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs2cache=0)
{
if ($nrows > 0) {
if ($offset <= 0) $str = " ROWS $nrows ";
else {
$a = $offset+1;
$b = $offset+$nrows;
$str = " ROWS $a TO $b";
}
} else {
// ok, skip
$a = $offset + 1;
$str = " ROWS $a TO 999999999"; // 999 million
}
$sql .= $str;
return ($secs2cache) ?
$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3)
:
$this->Execute($sql,$inputarr,$arg3);
}
};
class ADORecordSet_borland_ibase extends ADORecordSet_ibase {
var $databaseType = "borland_ibase";
function ADORecordSet_borland_ibase($id,$mode=false)
{
$this->ADORecordSet_ibase($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Support Borland Interbase 6.5 and later
*/
include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
class ADODB_borland_ibase extends ADODB_ibase {
var $databaseType = "borland_ibase";
function ADODB_borland_ibase()
{
$this->ADODB_ibase();
}
function ServerInfo()
{
$arr['dialect'] = $this->dialect;
switch($arr['dialect']) {
case '':
case '1': $s = 'Interbase 6.5, Dialect 1'; break;
case '2': $s = 'Interbase 6.5, Dialect 2'; break;
default:
case '3': $s = 'Interbase 6.5, Dialect 3'; break;
}
$arr['version'] = '6.5';
$arr['description'] = $s;
return $arr;
}
/* Note that Interbase 6.5 uses ROWS instead - don't you love forking wars! */
/* SELECT col1, col2 FROM table ROWS 5 -- get 5 rows */
/* SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2 */
/* Firebird uses */
/* SELECT FIRST 5 SKIP 2 col1, col2 FROM TABLE */
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs2cache=0)
{
if ($nrows > 0) {
if ($offset <= 0) $str = " ROWS $nrows ";
else {
$a = $offset+1;
$b = $offset+$nrows;
$str = " ROWS $a TO $b";
}
} else {
/* ok, skip */
$a = $offset + 1;
$str = " ROWS $a TO 999999999"; /* 999 million */
}
$sql .= $str;
return ($secs2cache) ?
$this->CacheExecute($secs2cache,$sql,$inputarr,$arg3)
:
$this->Execute($sql,$inputarr,$arg3);
}
};
class ADORecordSet_borland_ibase extends ADORecordSet_ibase {
var $databaseType = "borland_ibase";
function ADORecordSet_borland_ibase($id,$mode=false)
{
$this->ADORecordSet_ibase($id,$mode);
}
}
?>
+201 -201
View File
@@ -1,202 +1,202 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.
Native types have been converted to MetaTypes.
Transactions not supported yet.
*/
if (! defined("_ADODB_CSV_LAYER")) {
define("_ADODB_CSV_LAYER", 1 );
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
class ADODB_csv extends ADOConnection {
var $databaseType = 'csv';
var $databaseProvider = 'csv';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $_affectedrows=0;
var $_insertid=0;
var $_url;
var $replaceQuote = "''"; // string to use to replace quotes
var $hasTransactions = false;
var $_errorNo = false;
function ADODB_csv()
{
}
function _insertid()
{
return $this->_insertid;
}
function _affectedrows()
{
return $this->_affectedrows;
}
function &MetaDatabases()
{
return false;
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
$this->_url = $argHostname;
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (strtolower(substr($argHostname,0,7)) !== 'http://') return false;
$this->_url = $argHostname;
return true;
}
function &MetaColumns($table)
{
return false;
}
// parameters use PostgreSQL convention, not MySQL
function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)
{
global $ADODB_FETCH_MODE;
$url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".
(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).
"&offset=$offset&arg3=".urlencode($arg3);
$err = false;
$rs = csv2rs($url,$err,false);
if ($this->debug) print "$url<br><i>$err</i><br>";
$at = strpos($err,'::::');
if ($at === false) {
$this->_errorMsg = $err;
$this->_errorNo = (integer)$err;
} else {
$this->_errorMsg = substr($err,$at+4,1024);
$this->_errorNo = -9999;
}
if ($this->_errorNo)
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');
}
if (is_object($rs)) {
$rs->databaseType='csv';
$rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE;
$rs->connection = &$this;
}
return $rs;
}
// returns queryID or false
function &Execute($sql,$inputarr=false,$arg3=false)
{
global $ADODB_FETCH_MODE;
if (!$this->_bindInputArray && $inputarr) {
$sqlarr = explode('?',$sql);
$sql = '';
$i = 0;
foreach($inputarr as $v) {
$sql .= $sqlarr[$i];
// from Ron Baldwin <[email protected]>
// Only quote string types
if (gettype($v) == 'string')
$sql .= $this->qstr($v);
else if ($v === null)
$sql .= 'NULL';
else
$sql .= $v;
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
print "Input Array does not match ?: ".htmlspecialchars($sql);
$inputarr = false;
}
$url = $this->_url.'?sql='.urlencode($sql)."&fetch=".
(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);
if ($arg3) $url .= "&arg3=".urlencode($arg3);
$err = false;
$rs = csv2rs($url,$err,false);
if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";
$at = strpos($err,'::::');
if ($at === false) {
$this->_errorMsg = $err;
$this->_errorNo = (integer)$err;
} else {
$this->_errorMsg = substr($err,$at+4,1024);
$this->_errorNo = -9999;
}
if ($this->_errorNo)
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);
}
if (is_object($rs)) {
$rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE;
$this->_affectedrows = $rs->affectedrows;
$this->_insertid = $rs->insertid;
$rs->databaseType='csv';
$rs->connection = &$this;
}
return $rs;
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
return $this->_errorNo;
}
// returns true or false
function _close()
{
return true;
}
} // class
class ADORecordset_csv extends ADORecordset {
function ADORecordset_csv($id,$mode=false)
{
$this->ADORecordset($id,$mode);
}
function _close()
{
return true;
}
}
} // define
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Currently unsupported: MetaDatabases, MetaTables and MetaColumns, and also inputarr in Execute.
Native types have been converted to MetaTypes.
Transactions not supported yet.
*/
if (! defined("_ADODB_CSV_LAYER")) {
define("_ADODB_CSV_LAYER", 1 );
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
class ADODB_csv extends ADOConnection {
var $databaseType = 'csv';
var $databaseProvider = 'csv';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $_affectedrows=0;
var $_insertid=0;
var $_url;
var $replaceQuote = "''"; /* string to use to replace quotes */
var $hasTransactions = false;
var $_errorNo = false;
function ADODB_csv()
{
}
function _insertid()
{
return $this->_insertid;
}
function _affectedrows()
{
return $this->_affectedrows;
}
function &MetaDatabases()
{
return false;
}
/* returns true or false */
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (strtolower(substr($argHostname,0,7)) !== 'http:/* ') return false; */
$this->_url = $argHostname;
return true;
}
/* returns true or false */
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if (strtolower(substr($argHostname,0,7)) !== 'http:/* ') return false; */
$this->_url = $argHostname;
return true;
}
function &MetaColumns($table)
{
return false;
}
/* parameters use PostgreSQL convention, not MySQL */
function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)
{
global $ADODB_FETCH_MODE;
$url = $this->_url.'?sql='.urlencode($sql)."&nrows=$nrows&fetch=".
(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE).
"&offset=$offset&arg3=".urlencode($arg3);
$err = false;
$rs = csv2rs($url,$err,false);
if ($this->debug) print "$url<br><i>$err</i><br>";
$at = strpos($err,'::::');
if ($at === false) {
$this->_errorMsg = $err;
$this->_errorNo = (integer)$err;
} else {
$this->_errorMsg = substr($err,$at+4,1024);
$this->_errorNo = -9999;
}
if ($this->_errorNo)
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,'');
}
if (is_object($rs)) {
$rs->databaseType='csv';
$rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE;
$rs->connection = &$this;
}
return $rs;
}
/* returns queryID or false */
function &Execute($sql,$inputarr=false,$arg3=false)
{
global $ADODB_FETCH_MODE;
if (!$this->_bindInputArray && $inputarr) {
$sqlarr = explode('?',$sql);
$sql = '';
$i = 0;
foreach($inputarr as $v) {
$sql .= $sqlarr[$i];
/* from Ron Baldwin <[email protected]> */
/* Only quote string types */
if (gettype($v) == 'string')
$sql .= $this->qstr($v);
else if ($v === null)
$sql .= 'NULL';
else
$sql .= $v;
$i += 1;
}
$sql .= $sqlarr[$i];
if ($i+1 != sizeof($sqlarr))
print "Input Array does not match ?: ".htmlspecialchars($sql);
$inputarr = false;
}
$url = $this->_url.'?sql='.urlencode($sql)."&fetch=".
(($this->fetchMode !== false)?$this->fetchMode : $ADODB_FETCH_MODE);
if ($arg3) $url .= "&arg3=".urlencode($arg3);
$err = false;
$rs = csv2rs($url,$err,false);
if ($this->debug) print urldecode($url)."<br><i>$err</i><br>";
$at = strpos($err,'::::');
if ($at === false) {
$this->_errorMsg = $err;
$this->_errorNo = (integer)$err;
} else {
$this->_errorMsg = substr($err,$at+4,1024);
$this->_errorNo = -9999;
}
if ($this->_errorNo)
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr);
}
if (is_object($rs)) {
$rs->fetchMode = ($this->fetchMode !== false) ? $this->fetchMode : $ADODB_FETCH_MODE;
$this->_affectedrows = $rs->affectedrows;
$this->_insertid = $rs->insertid;
$rs->databaseType='csv';
$rs->connection = &$this;
}
return $rs;
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
return $this->_errorNo;
}
/* returns true or false */
function _close()
{
return true;
}
} /* class */
class ADORecordset_csv extends ADORecordset {
function ADORecordset_csv($id,$mode=false)
{
$this->ADORecordset($id,$mode);
}
function _close()
{
return true;
}
}
} /* define */
?>
+264 -195
View File
@@ -1,196 +1,265 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
DB2 data driver. Requires ODBC.
From phpdb list:
Hi Andrew,
thanks a lot for your help. Today we discovered what
our real problem was:
After "playing" a little bit with the php-scripts that try
to connect to the IBM DB2, we set the optional parameter
Cursortype when calling odbc_pconnect(....).
And the exciting thing: When we set the cursor type
to SQL_CUR_USE_ODBC Cursor Type, then
the whole query speed up from 1 till 10 seconds
to 0.2 till 0.3 seconds for 100 records. Amazing!!!
Therfore, PHP is just almost fast as calling the DB2
from Servlets using JDBC (don't take too much care
about the speed at whole: the database was on a
completely other location, so the whole connection
was made over a slow network connection).
I hope this helps when other encounter the same
problem when trying to connect to DB2 from
PHP.
Kind regards,
Christian Szardenings
2 Oct 2001
Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by
IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.
From the IBM CLI Reference:
SQL_ATTR_ODBC_CURSORS (DB2 CLI v5)
This connection attribute is defined by ODBC, but is not supported by DB2
CLI. Any attempt to set or get this attribute will result in an SQLSTATE of
HYC00 (Driver not capable).
A 32-bit option specifying how the Driver Manager uses the ODBC cursor
library.
So I guess this means the message [above] was related to using a 3rd party
odbc driver.
Setting SQL_CUR_USE_ODBC
========================
To set SQL_CUR_USE_ODBC for drivers that require it, do this:
$db = NewADOConnection('db2');
$db->curMode = SQL_CUR_USE_ODBC;
$db->Connect($dsn, $userid, $pwd);
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_DB2')){
define('ADODB_DB2',1);
class ADODB_DB2 extends ADODB_odbc {
var $databaseType = "db2";
var $concat_operator = 'CONCAT';
var $sysDate = 'CURRENT DATE';
var $sysTimeStamp = 'CURRENT TIMESTAMP';
var $ansiOuter = true;
//var $curmode = SQL_CUR_USE_ODBC;
function ADODB_DB2()
{
$this->ADODB_odbc();
}
function RowLock($tables,$where)
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
}
// Format date column in sql string given an input format that understands Y M D
function SQLDate($fmt, $col=false)
{
// use right() and replace() ?
if (!$col) $col = $this->sysDate;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '+';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "char(year($col))";
break;
case 'M':
case 'm':
$s .= "right(digits(month($col)),2)";
break;
case 'D':
case 'd':
$s .= "right(digits(day($col)),2)";
break;
default:
$s .= $this->qstr($ch);
}
}
return $s;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)
{
if ($offset <= 0) {
// could also use " OPTIMIZE FOR $nrows ROWS "
$sql .= " FETCH FIRST $nrows ROWS ONLY ";
return $this->Execute($sql,false,$arg3);
} else {
$nrows += $offset;
$sql .= " FETCH FIRST $nrows ROWS ONLY ";
return ADOConnection::SelectLimit($sql,-1,$offset,$arg3);
}
}
};
class ADORecordSet_db2 extends ADORecordSet_odbc {
var $databaseType = "db2";
function ADORecordSet_db2($id,$mode=false)
{
$this->ADORecordSet_odbc($id,$mode);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
switch (strtoupper($t)) {
case 'VARCHAR':
case 'CHAR':
case 'CHARACTER':
if ($len <= $this->blobSize) return 'C';
case 'LONGCHAR':
case 'TEXT':
case 'CLOB':
case 'DBCLOB': // double-byte
return 'X';
case 'BLOB':
case 'GRAPHIC':
case 'VARGRAPHIC':
return 'B';
case 'DATE':
return 'D';
case 'TIME':
case 'TIMESTAMP':
return 'T';
//case 'BOOLEAN':
//case 'BIT':
// return 'L';
//case 'COUNTER':
// return 'R';
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'SMALLINT':
return 'I';
default: return 'N';
}
}
}
} //define
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
DB2 data driver. Requires ODBC.
From phpdb list:
Hi Andrew,
thanks a lot for your help. Today we discovered what
our real problem was:
After "playing" a little bit with the php-scripts that try
to connect to the IBM DB2, we set the optional parameter
Cursortype when calling odbc_pconnect(....).
And the exciting thing: When we set the cursor type
to SQL_CUR_USE_ODBC Cursor Type, then
the whole query speed up from 1 till 10 seconds
to 0.2 till 0.3 seconds for 100 records. Amazing!!!
Therfore, PHP is just almost fast as calling the DB2
from Servlets using JDBC (don't take too much care
about the speed at whole: the database was on a
completely other location, so the whole connection
was made over a slow network connection).
I hope this helps when other encounter the same
problem when trying to connect to DB2 from
PHP.
Kind regards,
Christian Szardenings
2 Oct 2001
Mark Newnham has discovered that the SQL_CUR_USE_ODBC is not supported by
IBM's DB2 ODBC driver, so this must be a 3rd party ODBC driver.
From the IBM CLI Reference:
SQL_ATTR_ODBC_CURSORS (DB2 CLI v5)
This connection attribute is defined by ODBC, but is not supported by DB2
CLI. Any attempt to set or get this attribute will result in an SQLSTATE of
HYC00 (Driver not capable).
A 32-bit option specifying how the Driver Manager uses the ODBC cursor
library.
So I guess this means the message [above] was related to using a 3rd party
odbc driver.
Setting SQL_CUR_USE_ODBC
========================
To set SQL_CUR_USE_ODBC for drivers that require it, do this:
$db = NewADOConnection('db2');
$db->curMode = SQL_CUR_USE_ODBC;
$db->Connect($dsn, $userid, $pwd);
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_DB2')){
define('ADODB_DB2',1);
class ADODB_DB2 extends ADODB_odbc {
var $databaseType = "db2";
var $concat_operator = '||';
var $sysDate = 'CURRENT_DATE';
var $sysTimeStamp = 'CURRENT TIMESTAMP';
var $ansiOuter = true;
var $identitySQL = 'values IDENTITY_VAL_LOCAL()';
function ADODB_DB2()
{
if (strpos(PHP_OS,'WIN') !== false) $this->curmode = SQL_CUR_USE_ODBC;
$this->ADODB_odbc();
}
function ServerInfo()
{
/* odbc_setoption($this->_connectionID,1,101 /*SQL_ATTR_ACCESS_MODE*/, 1 /*SQL_MODE_READ_ONLY*/); */
$vers = $this->GetOne('select versionnumber from sysibm.sysversions');
/* odbc_setoption($this->_connectionID,1,101, 0 /*SQL_MODE_READ_WRITE*/); */
return array('description'=>'DB2 ODBC driver', 'version'=>$vers);
}
function _insertid()
{
return $this->GetOne($this->identitySQL);
}
function RowLock($tables,$where)
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
}
function &MetaTables($showSchema=false)
{
global $ADODB_FETCH_MODE;
$savem = $ADODB_FETCH_MODE;
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
$qid = odbc_tables($this->_connectionID);
$rs = new ADORecordSet_odbc($qid);
$ADODB_FETCH_MODE = $savem;
if (!$rs) return false;
$rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
/* print_r($rs); */
$arr =& $rs->GetArray();
$rs->Close();
$arr2 = array();
/* print_r($arr); */
for ($i=0; $i < sizeof($arr); $i++) {
$row = $arr[$i];
if ($row[2] && strncmp($row[1],'SYS',3) != 0)
if ($showSchema) $arr2[] = $row[1].'.'.$row[2];
else $arr2[] = $row[2];
}
return $arr2;
}
/* Format date column in sql string given an input format that understands Y M D */
function SQLDate($fmt, $col=false)
{
/* use right() and replace() ? */
if (!$col) $col = $this->sysDate;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '||';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "char(year($col))";
break;
case 'M':
$s .= "substr(monthname($col),1,3)";
break;
case 'm':
$s .= "right(digits(month($col)),2)";
break;
case 'D':
case 'd':
$s .= "right(digits(day($col)),2)";
break;
case 'H':
case 'h':
if ($col != $this->sysDate) $s .= "right(digits(hour($col)),2)";
else $s .= "''";
break;
case 'i':
case 'I':
if ($col != $this->sysDate)
$s .= "right(digits(minute($col)),2)";
else $s .= "''";
break;
case 'S':
case 's':
if ($col != $this->sysDate)
$s .= "right(digits(second($col)),2)";
else $s .= "''";
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $this->qstr($ch);
}
}
return $s;
}
function &SelectLimit($sql,$nrows=-1,$offset=-1,$arg3=false)
{
if ($offset <= 0) {
/* could also use " OPTIMIZE FOR $nrows ROWS " */
if ($nrows >= 0) $sql .= " FETCH FIRST $nrows ROWS ONLY ";
return $this->Execute($sql,false,$arg3);
} else {
if ($offset > 0 && $nrows < 0);
else {
$nrows += $offset;
$sql .= " FETCH FIRST $nrows ROWS ONLY ";
}
return ADOConnection::SelectLimit($sql,-1,$offset,$arg3);
}
}
};
class ADORecordSet_db2 extends ADORecordSet_odbc {
var $databaseType = "db2";
function ADORecordSet_db2($id,$mode=false)
{
$this->ADORecordSet_odbc($id,$mode);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
switch (strtoupper($t)) {
case 'VARCHAR':
case 'CHAR':
case 'CHARACTER':
if ($len <= $this->blobSize) return 'C';
case 'LONGCHAR':
case 'TEXT':
case 'CLOB':
case 'DBCLOB': /* double-byte */
return 'X';
case 'BLOB':
case 'GRAPHIC':
case 'VARGRAPHIC':
return 'B';
case 'DATE':
return 'D';
case 'TIME':
case 'TIMESTAMP':
return 'T';
/* case 'BOOLEAN': */
/* case 'BIT': */
/* return 'L'; */
/* case 'COUNTER': */
/* return 'R'; */
case 'INT':
case 'INTEGER':
case 'BIGINT':
case 'SMALLINT':
return 'I';
default: return 'N';
}
}
}
} /* define */
?>
+261 -261
View File
@@ -1,262 +1,262 @@
<?php
/*
@version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Contribution by Frank M. Kromann <[email protected]>.
Set tabs to 8.
*/
if (! defined("_ADODB_FBSQL_LAYER")) {
define("_ADODB_FBSQL_LAYER", 1 );
class ADODB_fbsql extends ADOConnection {
var $databaseType = 'fbsql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = false;
function ADODB_fbsql()
{
}
function _insertid()
{
return fbsql_insert_id($this->_connectionID);
}
function _affectedrows()
{
return fbsql_affected_rows($this->_connectionID);
}
function &MetaDatabases()
{
$qid = fbsql_list_dbs($this->_connectionID);
$arr = array();
$i = 0;
$max = fbsql_num_rows($qid);
while ($i < $max) {
$arr[] = fbsql_tablename($qid,$i);
$i += 1;
}
return $arr;
}
// returns concatenated string
function Concat()
{
$s = "";
$arr = func_get_args();
$first = true;
$s = implode(',',$arr);
if (sizeof($arr) > 0) return "CONCAT($s)";
else return '';
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
// split type into type(length):
if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
} else {
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($fld->type,'blob') !== false);
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
// returns true or false
function SelectDB($dbName)
{
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @fbsql_select_db($dbName,$this->_connectionID);
}
else return false;
}
// returns queryID or false
function _query($sql,$inputarr)
{
return fbsql_query("$sql;",$this->_connectionID);
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
$this->_errorMsg = @fbsql_error($this->_connectionID);
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
return @fbsql_errno($this->_connectionID);
}
// returns true or false
function _close()
{
return @fbsql_close($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_fbsql extends ADORecordSet{
var $databaseType = "fbsql";
var $canSeek = true;
function ADORecordSet_fbsql($queryID,$mode=false)
{
if (!$mode) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode) {
case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
default:
case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;
case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
}
return $this->ADORecordSet($queryID);
}
function _initrs()
{
GLOBAL $ADODB_COUNTRECS;
$this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;
$this->_numOfFields = @fbsql_num_fields($this->_queryID);
}
function &FetchField($fieldOffset = -1) {
if ($fieldOffset != -1) {
$o = @fbsql_fetch_field($this->_queryID, $fieldOffset);
//$o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable
$f = @fbsql_field_flags($this->_queryID,$fieldOffset);
$o->binary = (strpos($f,'binary')!== false);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @fbsql_fetch_field($this->_queryID);// fbsql returns the max length less spaces -- so it is unrealiable
//$o->max_length = -1;
}
return $o;
}
function _seek($row)
{
return @fbsql_data_seek($this->_queryID,$row);
}
function _fetch($ignore_fields=false)
{
$this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);
return ($this->fields == true);
}
function _close() {
return @fbsql_free_result($this->_queryID);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; // fbsql max_length is not accurate
switch (strtoupper($t)) {
case 'CHARACTER':
case 'CHARACTER VARYING':
case 'BLOB':
case 'CLOB':
case 'BIT':
case 'BIT VARYING':
if ($len <= $this->blobSize) return 'C';
// so we have to check whether binary...
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'DATE': return 'D';
case 'TIME':
case 'TIME WITH TIME ZONE':
case 'TIMESTAMP':
case 'TIMESTAMP WITH TIME ZONE': return 'T';
case 'PRIMARY_KEY':
return 'R';
case 'INTEGER':
case 'SMALLINT':
case 'BOOLEAN':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
}
}
} //class
} // defined
<?php
/*
@version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Contribution by Frank M. Kromann <[email protected]>.
Set tabs to 8.
*/
if (! defined("_ADODB_FBSQL_LAYER")) {
define("_ADODB_FBSQL_LAYER", 1 );
class ADODB_fbsql extends ADOConnection {
var $databaseType = 'fbsql';
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL = "SHOW TABLES";
var $metaColumnsSQL = "SHOW COLUMNS FROM %s";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasLimit = false;
function ADODB_fbsql()
{
}
function _insertid()
{
return fbsql_insert_id($this->_connectionID);
}
function _affectedrows()
{
return fbsql_affected_rows($this->_connectionID);
}
function &MetaDatabases()
{
$qid = fbsql_list_dbs($this->_connectionID);
$arr = array();
$i = 0;
$max = fbsql_num_rows($qid);
while ($i < $max) {
$arr[] = fbsql_tablename($qid,$i);
$i += 1;
}
return $arr;
}
/* returns concatenated string */
function Concat()
{
$s = "";
$arr = func_get_args();
$first = true;
$s = implode(',',$arr);
if (sizeof($arr) > 0) return "CONCAT($s)";
else return '';
}
/* returns true or false */
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = fbsql_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/* returns true or false */
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = fbsql_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
function &MetaColumns($table)
{
if ($this->metaColumnsSQL) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,$table));
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF){
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
/* split type into type(length): */
if (preg_match("/^(.+)\((\d+)\)$/", $fld->type, $query_array)) {
$fld->type = $query_array[1];
$fld->max_length = $query_array[2];
} else {
$fld->max_length = -1;
}
$fld->not_null = ($rs->fields[2] != 'YES');
$fld->primary_key = ($rs->fields[3] == 'PRI');
$fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false);
$fld->binary = (strpos($fld->type,'blob') !== false);
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
/* returns true or false */
function SelectDB($dbName)
{
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @fbsql_select_db($dbName,$this->_connectionID);
}
else return false;
}
/* returns queryID or false */
function _query($sql,$inputarr)
{
return fbsql_query("$sql;",$this->_connectionID);
}
/* Returns: the last error message from previous database operation */
function ErrorMsg()
{
$this->_errorMsg = @fbsql_error($this->_connectionID);
return $this->_errorMsg;
}
/* Returns: the last error number from previous database operation */
function ErrorNo()
{
return @fbsql_errno($this->_connectionID);
}
/* returns true or false */
function _close()
{
return @fbsql_close($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_fbsql extends ADORecordSet{
var $databaseType = "fbsql";
var $canSeek = true;
function ADORecordSet_fbsql($queryID,$mode=false)
{
if (!$mode) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
switch ($mode) {
case ADODB_FETCH_NUM: $this->fetchMode = FBSQL_NUM; break;
default:
case ADODB_FETCH_BOTH: $this->fetchMode = FBSQL_BOTH; break;
case ADODB_FETCH_ASSOC: $this->fetchMode = FBSQL_ASSOC; break;
}
return $this->ADORecordSet($queryID);
}
function _initrs()
{
GLOBAL $ADODB_COUNTRECS;
$this->_numOfRows = ($ADODB_COUNTRECS) ? @fbsql_num_rows($this->_queryID):-1;
$this->_numOfFields = @fbsql_num_fields($this->_queryID);
}
function &FetchField($fieldOffset = -1) {
if ($fieldOffset != -1) {
$o = @fbsql_fetch_field($this->_queryID, $fieldOffset);
/* $o->max_length = -1; // fbsql returns the max length less spaces -- so it is unrealiable */
$f = @fbsql_field_flags($this->_queryID,$fieldOffset);
$o->binary = (strpos($f,'binary')!== false);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @fbsql_fetch_field($this->_queryID);/* fbsql returns the max length less spaces -- so it is unrealiable */
/* $o->max_length = -1; */
}
return $o;
}
function _seek($row)
{
return @fbsql_data_seek($this->_queryID,$row);
}
function _fetch($ignore_fields=false)
{
$this->fields = @fbsql_fetch_array($this->_queryID,$this->fetchMode);
return ($this->fields == true);
}
function _close() {
return @fbsql_free_result($this->_queryID);
}
function MetaType($t,$len=-1,$fieldobj=false)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
$len = -1; /* fbsql max_length is not accurate */
switch (strtoupper($t)) {
case 'CHARACTER':
case 'CHARACTER VARYING':
case 'BLOB':
case 'CLOB':
case 'BIT':
case 'BIT VARYING':
if ($len <= $this->blobSize) return 'C';
/* so we have to check whether binary... */
case 'IMAGE':
case 'LONGBLOB':
case 'BLOB':
case 'MEDIUMBLOB':
return !empty($fieldobj->binary) ? 'B' : 'X';
case 'DATE': return 'D';
case 'TIME':
case 'TIME WITH TIME ZONE':
case 'TIMESTAMP':
case 'TIMESTAMP WITH TIME ZONE': return 'T';
case 'PRIMARY_KEY':
return 'R';
case 'INTEGER':
case 'SMALLINT':
case 'BOOLEAN':
if (!empty($fieldobj->primary_key)) return 'R';
else return 'I';
default: return 'N';
}
}
} /* class */
} /* defined */
?>
+66 -67
View File
@@ -1,68 +1,67 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
class ADODB_firebird extends ADODB_ibase {
var $databaseType = "firebird";
function ADODB_firebird()
{
$this->ADODB_ibase();
}
function ServerInfo()
{
$arr['dialect'] = $this->dialect;
switch($arr['dialect']) {
case '':
case '1': $s = 'Firebird Dialect 1'; break;
case '2': $s = 'Firebird Dialect 2'; break;
default:
case '3': $s = 'Firebird Dialect 3'; break;
}
$arr['version'] = ADOConnection::_findvers($s);
$arr['description'] = $s;
return $arr;
}
// Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars!
// SELECT col1, col2 FROM table ROWS 5 -- get 5 rows
// SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0)
{
$str = 'SELECT ';
if ($nrows >= 0) $str .= "FIRST $nrows ";
$str .=($offset>=0) ? "SKIP $offset " : '';
$sql = preg_replace('/^[ \t]*select/i',$str,$sql);
return ($secs) ?
$this->CacheExecute($secs,$sql,$inputarr,$arg3)
:
$this->Execute($sql,$inputarr,$arg3);
}
};
class ADORecordSet_firebird extends ADORecordSet_ibase {
var $databaseType = "firebird";
function ADORecordSet_firebird($id,$mode=false)
{
$this->ADORecordSet_ibase($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
include_once(ADODB_DIR."/drivers/adodb-ibase.inc.php");
class ADODB_firebird extends ADODB_ibase {
var $databaseType = "firebird";
function ADODB_firebird()
{
$this->ADODB_ibase();
}
function ServerInfo()
{
$arr['dialect'] = $this->dialect;
switch($arr['dialect']) {
case '':
case '1': $s = 'Firebird Dialect 1'; break;
case '2': $s = 'Firebird Dialect 2'; break;
default:
case '3': $s = 'Firebird Dialect 3'; break;
}
$arr['version'] = ADOConnection::_findvers($s);
$arr['description'] = $s;
return $arr;
}
/* Note that Interbase 6.5 uses this ROWS instead - don't you love forking wars! */
/* SELECT col1, col2 FROM table ROWS 5 -- get 5 rows */
/* SELECT col1, col2 FROM TABLE ORDER BY col1 ROWS 3 TO 7 -- first 5 skip 2 */
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false, $arg3=false,$secs=0)
{
$str = 'SELECT ';
if ($nrows >= 0) $str .= "FIRST $nrows ";
$str .=($offset>=0) ? "SKIP $offset " : '';
$sql = preg_replace('/^[ \t]*select/i',$str,$sql);
return ($secs) ?
$this->CacheExecute($secs,$sql,$inputarr,$arg3)
:
$this->Execute($sql,$inputarr,$arg3);
}
};
class ADORecordSet_firebird extends ADORecordSet_ibase {
var $databaseType = "firebird";
function ADORecordSet_firebird($id,$mode=false)
{
$this->ADORecordSet_ibase($id,$mode);
}
}
?>
File diff suppressed because it is too large Load Diff
+29 -29
View File
@@ -1,30 +1,30 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Informix 9 driver that supports SELECT FIRST
*
*/
include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');
class ADODB_informix extends ADODB_informix72 {
var $databaseType = "informix";
var $hasTop = 'FIRST';
var $ansiOuter = true;
}
class ADORecordset_informix extends ADORecordset_informix72 {
var $databaseType = "informix";
function ADORecordset_informix($id,$mode=false)
{
$this->ADORecordset_informix72($id,$mode);
}
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Informix 9 driver that supports SELECT FIRST
*
*/
include_once(ADODB_DIR.'/drivers/adodb-informix72.inc.php');
class ADODB_informix extends ADODB_informix72 {
var $databaseType = "informix";
var $hasTop = 'FIRST';
var $ansiOuter = true;
}
class ADORecordset_informix extends ADORecordset_informix72 {
var $databaseType = "informix";
function ADORecordset_informix($id,$mode=false)
{
$this->ADORecordset_informix72($id,$mode);
}
}
?>
+314 -313
View File
@@ -1,314 +1,315 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Informix port by Mitchell T. Young ([email protected])
Further mods by "Samuel CARRIERE" <[email protected]>
*/
class ADODB_informix72 extends ADOConnection {
var $databaseType = "informix72";
var $dataProvider = "informix";
var $replaceQuote = "''"; // string to use to replace quotes
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL="select tabname from systables";
var $metaColumnsSQL = "select colname, coltype, collength from syscolumns c, systables t where c.tabid=t.tabid and tabname='%s'";
var $concat_operator = '||';
var $lastQuery = false;
var $has_insertid = true;
var $_autocommit = true;
var $_bindInputArray = true; // set to true if ADOConnection.Execute() permits binding of array parameters.
var $sysDate = 'TODAY';
var $sysTimeStamp = 'CURRENT';
function ADODB_informix72()
{
// alternatively, use older method:
//putenv("DBDATE=Y4MD-");
// force ISO date format
putenv('GL_DATE=%Y-%m-%d');
}
function _insertid()
{
$sqlca =ifx_getsqlca($this->lastQuery);
return @$sqlca["sqlerrd1"];
}
function _affectedrows()
{
if ($this->lastQuery) {
return ifx_affected_rows ($this->lastQuery);
} else
return 0;
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('BEGIN');
$this->_autocommit = false;
return true;
}
function CommitTrans($ok=true)
{
if (!$ok) return $this->RollbackTrans();
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$this->_autocommit = true;
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->_autocommit = true;
return true;
}
function RowLock($tables,$where)
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
}
/* Returns: the last error message from previous database operation
Note: This function is NOT available for Microsoft SQL Server. */
function ErrorMsg() {
$this->_errorMsg = ifx_errormsg();
return $this->_errorMsg;
}
function ErrorNo()
{
return ifx_error();
}
function MetaColumns($table)
{
return ADOConnection::MetaColumns($table,false);
}
function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
{
$type = ($blobtype == 'TEXT') ? 1 : 0;
$blobid = ifx_create_blob($type,0,$val);
return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));
}
function BlobDecode($blobid)
{
return @ifx_get_blob($blobid);
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$dbs = $argDatabasename . "@" . $argHostname;
$this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
#if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$dbs = $argDatabasename . "@" . $argHostname;
$this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
#if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/*
// ifx_do does not accept bind parameters - wierd ???
function Prepare($sql)
{
$stmt = ifx_prepare($sql);
if (!$stmt) return $sql;
else return array($sql,$stmt);
}
*/
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
{
global $ADODB_COUNTRECS;
// String parameters have to be converted using ifx_create_char
if ($inputarr) {
foreach($inputarr as $v) {
if (gettype($v) == 'string') {
$tab[] = ifx_create_char($v);
}
else {
$tab[] = $v;
}
}
}
// In case of select statement, we use a scroll cursor in order
// to be able to call "move", or "movefirst" statements
if (!$ADODB_COUNTRECS && preg_match("/^\s*select/i", $sql)) {
if ($inputarr) {
$this->lastQuery = ifx_query($sql,$this->_connectionID, IFX_SCROLL, $tab);
}
else {
$this->lastQuery = ifx_query($sql,$this->_connectionID, IFX_SCROLL);
}
}
else {
if ($inputarr) {
$this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);
}
else {
$this->lastQuery = ifx_query($sql,$this->_connectionID);
}
}
// Following line have been commented because autocommit mode is
// not supported by informix SE 7.2
//if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID);
return $this->lastQuery;
}
// returns true or false
function _close()
{
$this->lastQuery = false;
return ifx_close($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_informix72 extends ADORecordSet {
var $databaseType = "informix72";
var $canSeek = true;
var $_fieldprops = false;
function ADORecordset_informix72($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
return $this->ADORecordSet($id);
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function &FetchField($fieldOffset = -1)
{
if (empty($this->_fieldprops)) {
$fp = ifx_fieldproperties($this->_queryID);
foreach($fp as $k => $v) {
$o = new ADOFieldObject;
$o->name = $k;
$arr = split(';',$v); //"SQLTYPE;length;precision;scale;ISNULLABLE"
$o->type = $arr[0];
$o->max_length = $arr[1];
$this->_fieldprops[] = $o;
}
}
return $this->_fieldprops[$fieldOffset];
}
function _initrs()
{
$this->_numOfRows = -1; // ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1;
$this->_numOfFields = ifx_num_fields($this->_queryID);
}
function _seek($row)
{
return @ifx_fetch_row($this->_queryID, $row);
}
function MoveLast()
{
$this->fields = @ifx_fetch_row($this->_queryID, "LAST");
if ($this->fields) $this->EOF = false;
$this->_currentRow = -1;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
function MoveFirst()
{
$this->fields = @ifx_fetch_row($this->_queryID, "FIRST");
if ($this->fields) $this->EOF = false;
$this->_currentRow = 0;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
function _fetch($ignore_fields=false)
{
$this->fields = @ifx_fetch_row($this->_queryID);
if (!is_array($this->fields)) return false;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
return ifx_free_result($this->_queryID);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Informix port by Mitchell T. Young ([email protected])
Further mods by "Samuel CARRIERE" <[email protected]>
*/
class ADODB_informix72 extends ADOConnection {
var $databaseType = "informix72";
var $dataProvider = "informix";
var $replaceQuote = "''"; /* string to use to replace quotes */
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL="select tabname from systables";
var $metaColumnsSQL = "select colname, coltype, collength from syscolumns c, systables t where c.tabid=t.tabid and tabname='%s'";
var $concat_operator = '||';
var $lastQuery = false;
var $has_insertid = true;
var $_autocommit = true;
var $_bindInputArray = true; /* set to true if ADOConnection.Execute() permits binding of array parameters. */
var $sysDate = 'TODAY';
var $sysTimeStamp = 'CURRENT';
function ADODB_informix72()
{
/* alternatively, use older method: */
/* putenv("DBDATE=Y4MD-"); */
/* force ISO date format */
putenv('GL_DATE=%Y-%m-%d');
}
function _insertid()
{
$sqlca =ifx_getsqlca($this->lastQuery);
return @$sqlca["sqlerrd1"];
}
function _affectedrows()
{
if ($this->lastQuery) {
return ifx_affected_rows ($this->lastQuery);
} else
return 0;
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('BEGIN');
$this->_autocommit = false;
return true;
}
function CommitTrans($ok=true)
{
if (!$ok) return $this->RollbackTrans();
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$this->_autocommit = true;
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->_autocommit = true;
return true;
}
function RowLock($tables,$where)
{
if ($this->_autocommit) $this->BeginTrans();
return $this->GetOne("select 1 as ignore from $tables where $where for update");
}
/* Returns: the last error message from previous database operation
Note: This function is NOT available for Microsoft SQL Server. */
function ErrorMsg() {
$this->_errorMsg = ifx_errormsg();
return $this->_errorMsg;
}
function ErrorNo()
{
return ifx_error();
}
function &MetaColumns($table)
{
return ADOConnection::MetaColumns($table,false);
}
function UpdateBlob($table, $column, $val, $where, $blobtype = 'BLOB')
{
$type = ($blobtype == 'TEXT') ? 1 : 0;
$blobid = ifx_create_blob($type,0,$val);
return $this->Execute("UPDATE $table SET $column=(?) WHERE $where",array($blobid));
}
function BlobDecode($blobid)
{
return @ifx_get_blob($blobid);
}
/* returns true or false */
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$dbs = $argDatabasename . "@" . $argHostname;
$this->_connectionID = ifx_connect($dbs,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
#if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/* returns true or false */
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$dbs = $argDatabasename . "@" . $argHostname;
$this->_connectionID = ifx_pconnect($dbs,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
#if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/*
// ifx_do does not accept bind parameters - wierd ???
function Prepare($sql)
{
$stmt = ifx_prepare($sql);
if (!$stmt) return $sql;
else return array($sql,$stmt);
}
*/
/* returns query ID if successful, otherwise false */
function _query($sql,$inputarr)
{
global $ADODB_COUNTRECS;
/* String parameters have to be converted using ifx_create_char */
if ($inputarr) {
foreach($inputarr as $v) {
if (gettype($v) == 'string') {
$tab[] = ifx_create_char($v);
}
else {
$tab[] = $v;
}
}
}
/* In case of select statement, we use a scroll cursor in order */
/* to be able to call "move", or "movefirst" statements */
if (!$ADODB_COUNTRECS && preg_match("/^\s*select/is", $sql)) {
if ($inputarr) {
$this->lastQuery = ifx_query($sql,$this->_connectionID, IFX_SCROLL, $tab);
}
else {
$this->lastQuery = ifx_query($sql,$this->_connectionID, IFX_SCROLL);
}
}
else {
if ($inputarr) {
$this->lastQuery = ifx_query($sql,$this->_connectionID, $tab);
}
else {
$this->lastQuery = ifx_query($sql,$this->_connectionID);
}
}
/* Following line have been commented because autocommit mode is */
/* not supported by informix SE 7.2 */
/* if ($this->_autocommit) ifx_query('COMMIT',$this->_connectionID); */
return $this->lastQuery;
}
/* returns true or false */
function _close()
{
$this->lastQuery = false;
return ifx_close($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_informix72 extends ADORecordSet {
var $databaseType = "informix72";
var $canSeek = true;
var $_fieldprops = false;
function ADORecordset_informix72($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
return $this->ADORecordSet($id);
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function &FetchField($fieldOffset = -1)
{
if (empty($this->_fieldprops)) {
$fp = ifx_fieldproperties($this->_queryID);
foreach($fp as $k => $v) {
$o = new ADOFieldObject;
$o->name = $k;
$arr = split(';',$v); /* "SQLTYPE;length;precision;scale;ISNULLABLE" */
$o->type = $arr[0];
$o->max_length = $arr[1];
$this->_fieldprops[] = $o;
$o->not_null = $arr[4]=="N";
}
}
return $this->_fieldprops[$fieldOffset];
}
function _initrs()
{
$this->_numOfRows = -1; /* ifx_affected_rows not reliable, only returns estimate -- ($ADODB_COUNTRECS)? ifx_affected_rows($this->_queryID):-1; */
$this->_numOfFields = ifx_num_fields($this->_queryID);
}
function _seek($row)
{
return @ifx_fetch_row($this->_queryID, $row);
}
function MoveLast()
{
$this->fields = @ifx_fetch_row($this->_queryID, "LAST");
if ($this->fields) $this->EOF = false;
$this->_currentRow = -1;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
function MoveFirst()
{
$this->fields = @ifx_fetch_row($this->_queryID, "FIRST");
if ($this->fields) $this->EOF = false;
$this->_currentRow = 0;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
function _fetch($ignore_fields=false)
{
$this->fields = @ifx_fetch_row($this->_queryID);
if (!is_array($this->fields)) return false;
if ($this->fetchMode == ADODB_FETCH_NUM) {
foreach($this->fields as $v) {
$arr[] = $v;
}
$this->fields = $arr;
}
return true;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
return ifx_free_result($this->_queryID);
}
}
?>
File diff suppressed because it is too large Load Diff
+58 -58
View File
@@ -1,59 +1,59 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Portable MSSQL Driver that supports || instead of +
*
*/
/*
The big difference between mssqlpo and it's parent mssql is that mssqlpo supports
the more standard || string concatenation operator.
*/
include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
class ADODB_mssqlpo extends ADODB_mssql {
var $databaseType = "mssqlpo";
var $concat_operator = '||';
function ADODB_mssqlpo()
{
ADODB_mssql::ADODB_mssql();
}
function PrepareSP($sql)
{
if (!$this->_has_mssql_init) {
ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
return $sql;
}
if (is_string($sql)) $sql = str_replace('||','+',$sql);
$stmt = mssql_init($sql,$this->_connectionID);
if (!$stmt) return $sql;
return array($sql,$stmt);
}
function _query($sql,$inputarr)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_mssql::_query($sql,$inputarr);
}
}
class ADORecordset_mssqlpo extends ADORecordset_mssql {
var $databaseType = "mssqlpo";
function ADORecordset_mssqlpo($id,$mode=false)
{
$this->ADORecordset_mssql($id,$mode);
}
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Portable MSSQL Driver that supports || instead of +
*
*/
/*
The big difference between mssqlpo and it's parent mssql is that mssqlpo supports
the more standard || string concatenation operator.
*/
include_once(ADODB_DIR.'/drivers/adodb-mssql.inc.php');
class ADODB_mssqlpo extends ADODB_mssql {
var $databaseType = "mssqlpo";
var $concat_operator = '||';
function ADODB_mssqlpo()
{
ADODB_mssql::ADODB_mssql();
}
function PrepareSP($sql)
{
if (!$this->_has_mssql_init) {
ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
return $sql;
}
if (is_string($sql)) $sql = str_replace('||','+',$sql);
$stmt = mssql_init($sql,$this->_connectionID);
if (!$stmt) return $sql;
return array($sql,$stmt);
}
function _query($sql,$inputarr)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_mssql::_query($sql,$inputarr);
}
}
class ADORecordset_mssqlpo extends ADORecordset_mssql {
var $databaseType = "mssqlpo";
function ADORecordset_mssqlpo($id,$mode=false)
{
$this->ADORecordset_mssql($id,$mode);
}
}
?>
File diff suppressed because it is too large Load Diff
+75 -75
View File
@@ -1,76 +1,76 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
MySQL code that supports transactions. For MySQL 3.23 or later.
Code from James Poon <[email protected]>
Requires mysql client. Works on Windows and Unix.
*/
include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");
class ADODB_mysqlt extends ADODB_mysql {
var $databaseType = 'mysqlt';
var $ansiOuter = true; // for Version 3.23.17 or later
var $hasTransactions = true;
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('SET AUTOCOMMIT=0');
$this->Execute('BEGIN');
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
}
class ADORecordSet_mysqlt extends ADORecordSet_mysql{
var $databaseType = "mysqlt";
function ADORecordSet_mysqlt($queryID,$mode=false) {
return $this->ADORecordSet_mysql($queryID,$mode);
}
function MoveNext()
{
if ($this->EOF) return false;
$this->_currentRow++;
// using & below slows things down by 20%!
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
if ($this->fields) return true;
$this->EOF = true;
return false;
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
MySQL code that supports transactions. For MySQL 3.23 or later.
Code from James Poon <[email protected]>
Requires mysql client. Works on Windows and Unix.
*/
include_once(ADODB_DIR."/drivers/adodb-mysql.inc.php");
class ADODB_mysqlt extends ADODB_mysql {
var $databaseType = 'mysqlt';
var $ansiOuter = true; /* for Version 3.23.17 or later */
var $hasTransactions = true;
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('SET AUTOCOMMIT=0');
$this->Execute('BEGIN');
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('COMMIT');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
if ($this->transCnt) $this->transCnt -= 1;
$this->Execute('ROLLBACK');
$this->Execute('SET AUTOCOMMIT=1');
return true;
}
}
class ADORecordSet_mysqlt extends ADORecordSet_mysql{
var $databaseType = "mysqlt";
function ADORecordSet_mysqlt($queryID,$mode=false) {
return $this->ADORecordSet_mysql($queryID,$mode);
}
function MoveNext()
{
if ($this->EOF) return false;
$this->_currentRow++;
/* using & below slows things down by 20%! */
$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
if ($this->fields) return true;
$this->EOF = true;
return false;
}
}
?>
File diff suppressed because it is too large Load Diff
+55 -55
View File
@@ -1,56 +1,56 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Oracle 8.0.5 driver
*/
include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
class ADODB_oci805 extends ADODB_oci8 {
var $databaseType = "oci805";
var $connectSID = true;
function ADODB_oci805()
{
$this->ADODB_oci8();
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)
{
// seems that oracle only supports 1 hint comment in 8i
if (strpos($sql,'/*+') !== false)
$sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
else
$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
/*
The following is only available from 8.1.5 because order by in inline views not
available before then...
http://www.jlcomp.demon.co.uk/faq/top_sql.html
if ($nrows > 0) {
if ($offset > 0) $nrows += $offset;
$sql = "select * from ($sql) where rownum <= $nrows";
$nrows = -1;
}
*/
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
}
}
class ADORecordset_oci805 extends ADORecordset_oci8 {
var $databaseType = "oci805";
function ADORecordset_oci805($id,$mode=false)
{
$this->ADORecordset_oci8($id,$mode);
}
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Oracle 8.0.5 driver
*/
include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
class ADODB_oci805 extends ADODB_oci8 {
var $databaseType = "oci805";
var $connectSID = true;
function ADODB_oci805()
{
$this->ADODB_oci8();
}
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)
{
/* seems that oracle only supports 1 hint comment in 8i */
if (strpos($sql,'/*+') !== false)
$sql = str_replace('/*+ ','/*+FIRST_ROWS ',$sql);
else
$sql = preg_replace('/^[ \t\n]*select/i','SELECT /*+FIRST_ROWS*/',$sql);
/*
The following is only available from 8.1.5 because order by in inline views not
available before then...
http://www.jlcomp.demon.co.uk/faq/top_sql.html
if ($nrows > 0) {
if ($offset > 0) $nrows += $offset;
$sql = "select * from ($sql) where rownum <= $nrows";
$nrows = -1;
}
*/
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
}
}
class ADORecordset_oci805 extends ADORecordset_oci8 {
var $databaseType = "oci805";
function ADORecordset_oci805($id,$mode=false)
{
$this->ADORecordset_oci8($id,$mode);
}
}
?>
+165 -165
View File
@@ -1,166 +1,166 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Latest version is available at http://php.weblogs.com/
Portable version of oci8 driver, to make it more similar to other database drivers.
The main differences are
1. that the OCI_ASSOC names are in lowercase instead of uppercase.
2. bind variables are mapped using ? instead of :<bindvar>
Should some emulation of RecordCount() be implemented?
*/
include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
class ADODB_oci8po extends ADODB_oci8 {
var $databaseType = 'oci8po';
var $dataProvider = 'oci8';
var $metaColumnsSQL = "select lower(cname),coltype,width from col where tname='%s' order by colno";
var $metaTablesSQL = "select lower(table_name) from cat where table_type in ('TABLE','VIEW')";
function Prepare($sql)
{
$sqlarr = explode('?',$sql);
$sql = $sqlarr[0];
for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
$sql .= ':'.($i-1) . $sqlarr[$i];
}
return ADODB_oci8::Prepare($sql);
}
// emulate handling of parameters ? ?, replacing with :bind0 :bind1
function _query($sql,$inputarr)
{
if (is_array($inputarr)) {
$i = 0;
if (is_array($sql)) {
foreach($inputarr as $v) {
$arr['bind'.$i++] = $v;
}
} else {
$sqlarr = explode('?',$sql);
$sql = $sqlarr[0];
foreach($inputarr as $k => $v) {
$sql .= ":$k" . $sqlarr[++$i];
}
}
}
return ADODB_oci8::_query($sql,$inputarr);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_oci8po extends ADORecordset_oci8 {
var $databaseType = 'oci8po';
function ADORecordset_oci8po($queryID,$mode=false)
{
$this->ADORecordset_oci8($queryID,$mode);
}
function Fields($colname)
{
if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
// lowercase field names...
function &_FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fieldOffset += 1;
$fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
if ($fld->type == 'NUMBER') {
//$p = OCIColumnPrecision($this->_queryID, $fieldOffset);
$sc = OCIColumnScale($this->_queryID, $fieldOffset);
if ($sc == 0) $fld->type = 'INT';
}
return $fld;
}
// 10% speedup to move MoveNext to child class
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
return true;
}
$this->EOF = true;
}
return false;
}
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) return $this->GetArray($nrows);
for ($i=1; $i < $offset; $i++)
if (!@OCIFetch($this->_queryID)) return array();
if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
$results = array();
$cnt = 0;
while (!$this->EOF && $nrows != $cnt) {
$results[$cnt++] = $this->fields;
$this->MoveNext();
}
return $results;
}
// Create associative array
function _updatefields()
{
if (ADODB_ASSOC_CASE == 2) return; // native
$arr = array();
$lowercase = ADODB_ASSOC_CASE == 0;
foreach ($this->fields as $k => $v) {
if (is_integer($k)) $arr[$k] = $v;
else {
if ($lowercase)
$arr[strtolower($k)] = $v;
else
$arr[strtoupper($k)] = $v;
}
}
$this->fields = $arr;
}
function _fetch()
{
$ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
if ($ret) {
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
}
return $ret;
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Latest version is available at http://php.weblogs.com/
Portable version of oci8 driver, to make it more similar to other database drivers.
The main differences are
1. that the OCI_ASSOC names are in lowercase instead of uppercase.
2. bind variables are mapped using ? instead of :<bindvar>
Should some emulation of RecordCount() be implemented?
*/
include_once(ADODB_DIR.'/drivers/adodb-oci8.inc.php');
class ADODB_oci8po extends ADODB_oci8 {
var $databaseType = 'oci8po';
var $dataProvider = 'oci8';
var $metaColumnsSQL = "select lower(cname),coltype,width, SCALE, PRECISION, NULLS, DEFAULTVAL from col where tname='%s' order by colno"; /* changed by [email protected]. net */
var $metaTablesSQL = "select lower(table_name) from cat where table_type in ('TABLE','VIEW')";
function Prepare($sql)
{
$sqlarr = explode('?',$sql);
$sql = $sqlarr[0];
for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
$sql .= ':'.($i-1) . $sqlarr[$i];
}
return ADODB_oci8::Prepare($sql);
}
/* emulate handling of parameters ? ?, replacing with :bind0 :bind1 */
function _query($sql,$inputarr)
{
if (is_array($inputarr)) {
$i = 0;
if (is_array($sql)) {
foreach($inputarr as $v) {
$arr['bind'.$i++] = $v;
}
} else {
$sqlarr = explode('?',$sql);
$sql = $sqlarr[0];
foreach($inputarr as $k => $v) {
$sql .= ":$k" . $sqlarr[++$i];
}
}
}
return ADODB_oci8::_query($sql,$inputarr);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_oci8po extends ADORecordset_oci8 {
var $databaseType = 'oci8po';
function ADORecordset_oci8po($queryID,$mode=false)
{
$this->ADORecordset_oci8($queryID,$mode);
}
function Fields($colname)
{
if ($this->fetchMode & OCI_ASSOC) return $this->fields[$colname];
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
/* lowercase field names... */
function &_FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fieldOffset += 1;
$fld->name = strtolower(OCIcolumnname($this->_queryID, $fieldOffset));
$fld->type = OCIcolumntype($this->_queryID, $fieldOffset);
$fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset);
if ($fld->type == 'NUMBER') {
/* $p = OCIColumnPrecision($this->_queryID, $fieldOffset); */
$sc = OCIColumnScale($this->_queryID, $fieldOffset);
if ($sc == 0) $fld->type = 'INT';
}
return $fld;
}
/* 10% speedup to move MoveNext to child class */
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) {
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
return true;
}
$this->EOF = true;
}
return false;
}
/* Optimize SelectLimit() by using OCIFetch() instead of OCIFetchInto() */
function &GetArrayLimit($nrows,$offset=-1)
{
if ($offset <= 0) return $this->GetArray($nrows);
for ($i=1; $i < $offset; $i++)
if (!@OCIFetch($this->_queryID)) return array();
if (!@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) return array();
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
$results = array();
$cnt = 0;
while (!$this->EOF && $nrows != $cnt) {
$results[$cnt++] = $this->fields;
$this->MoveNext();
}
return $results;
}
/* Create associative array */
function _updatefields()
{
if (ADODB_ASSOC_CASE == 2) return; /* native */
$arr = array();
$lowercase = ADODB_ASSOC_CASE == 0;
foreach ($this->fields as $k => $v) {
if (is_integer($k)) $arr[$k] = $v;
else {
if ($lowercase)
$arr[strtolower($k)] = $v;
else
$arr[strtoupper($k)] = $v;
}
}
$this->fields = $arr;
}
function _fetch()
{
$ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode);
if ($ret) {
if ($this->fetchMode & OCI_ASSOC) $this->_updatefields();
}
return $ret;
}
}
?>
File diff suppressed because it is too large Load Diff
+163 -134
View File
@@ -1,135 +1,164 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix.
For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
class ADODB_odbc_mssql extends ADODB_odbc {
var $databaseType = 'odbc_mssql';
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d h:i:sA'";
var $_bindInputArray = true;
var $metaTablesSQL="select name from sysobjects where type='U' or type='V' and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))";
var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
var $hasTop = 'top'; // support mssql/interbase SELECT TOP 10 * FROM TABLE
var $sysDate = 'GetDate()';
var $sysTimeStamp = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; // for mssql7 or later
var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
var $hasInsertID = true;
function ADODB_odbc_mssql()
{
$this->ADODB_odbc();
}
function xServerInfo()
{
$row = $this->GetRow("execute sp_server_info 2");
$arr['description'] = $row[2];
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
function _insertid()
{
// SCOPE_IDENTITY()
// Returns the last IDENTITY value inserted into an IDENTITY column in
// the same scope. A scope is a module -- a stored procedure, trigger,
// function, or batch. Thus, two statements are in the same scope if
// they are in the same stored procedure, function, or batch.
return $this->GetOne($this->identitySQL);
}
function MetaTables()
{
return ADOConnection::MetaTables();
}
function MetaColumns($table)
{
return ADOConnection::MetaColumns($table);
}
// "Stein-Aksel Basma" <[email protected]>
// tested with MSSQL 2000
function MetaPrimaryKeys($table)
{
$sql = "select k.column_name from information_schema.key_column_usage k,
information_schema.table_constraints tc
where tc.constraint_name = k.constraint_name and tc.constraint_type =
'PRIMARY KEY' and k.table_name = '$table'";
$a = $this->GetCol($sql);
if ($a && sizeof($a)>0) return $a;
return false;
}
// 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;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '+';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "datename(yyyy,$col)";
break;
case 'M':
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
$s .= "datename(quarter,$col)";
break;
case 'D':
case 'd':
$s .= "replace(str(day($col),2),' ','0')";
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $this->qstr($ch);
break;
}
}
return $s;
}
}
class ADORecordSet_odbc_mssql extends ADORecordSet_odbc {
var $databaseType = 'odbc_mssql';
function ADORecordSet_odbc_mssql($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
MSSQL support via ODBC. Requires ODBC. Works on Windows and Unix.
For Unix configuration, see http://phpbuilder.com/columns/alberto20000919.php3
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
class ADODB_odbc_mssql extends ADODB_odbc {
var $databaseType = 'odbc_mssql';
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d h:i:sA'";
var $_bindInputArray = true;
var $metaTablesSQL="select name from sysobjects where type='U' or type='V' and (name not in ('sysallocations','syscolumns','syscomments','sysdepends','sysfilegroups','sysfiles','sysfiles1','sysforeignkeys','sysfulltextcatalogs','sysindexes','sysindexkeys','sysmembers','sysobjects','syspermissions','sysprotects','sysreferences','systypes','sysusers','sysalternates','sysconstraints','syssegments','REFERENTIAL_CONSTRAINTS','CHECK_CONSTRAINTS','CONSTRAINT_TABLE_USAGE','CONSTRAINT_COLUMN_USAGE','VIEWS','VIEW_TABLE_USAGE','VIEW_COLUMN_USAGE','SCHEMATA','TABLES','TABLE_CONSTRAINTS','TABLE_PRIVILEGES','COLUMNS','COLUMN_DOMAIN_USAGE','COLUMN_PRIVILEGES','DOMAINS','DOMAIN_CONSTRAINTS','KEY_COLUMN_USAGE'))";
var $metaColumnsSQL = "select c.name,t.name,c.length from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
var $hasTop = 'top'; /* support mssql/interbase SELECT TOP 10 * FROM TABLE */
var $sysDate = 'GetDate()';
var $sysTimeStamp = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
var $ansiOuter = true; /* for mssql7 or later */
var $identitySQL = 'select @@IDENTITY'; /* 'select SCOPE_IDENTITY'; # for mssql 2000 */
var $hasInsertID = true;
var $connectStmt = 'SET CONCAT_NULL_YIELDS_NULL OFF'; # When SET CONCAT_NULL_YIELDS_NULL is ON,
# concatenating a null value with a string yields a NULL result
function ADODB_odbc_mssql()
{
$this->ADODB_odbc();
}
/* crashes php... */
function xServerInfo()
{
$row = $this->GetRow("execute sp_server_info 2");
$arr['description'] = $row[2];
$arr['version'] = ADOConnection::_findvers($arr['description']);
return $arr;
}
function _insertid()
{
/* SCOPE_IDENTITY() */
/* Returns the last IDENTITY value inserted into an IDENTITY column in */
/* the same scope. A scope is a module -- a stored procedure, trigger, */
/* function, or batch. Thus, two statements are in the same scope if */
/* they are in the same stored procedure, function, or batch. */
return $this->GetOne($this->identitySQL);
}
function &MetaTables()
{
return ADOConnection::MetaTables();
}
function &MetaColumns($table)
{
return ADOConnection::MetaColumns($table);
}
function _query($sql,$inputarr)
{
if (is_string($sql)) $sql = str_replace('||','+',$sql);
return ADODB_odbc::_query($sql,$inputarr);
}
/* "Stein-Aksel Basma" <[email protected]> */
/* tested with MSSQL 2000 */
function &MetaPrimaryKeys($table)
{
$sql = "select k.column_name from information_schema.key_column_usage k,
information_schema.table_constraints tc
where tc.constraint_name = k.constraint_name and tc.constraint_type =
'PRIMARY KEY' and k.table_name = '$table'";
$a = $this->GetCol($sql);
if ($a && sizeof($a)>0) return $a;
return false;
}
/* Format date column in sql string given an input format that understands Y M D */
function SQLDate($fmt, $col=false)
{
if (!$col) $col = $this->sysTimeStamp;
$s = '';
$len = strlen($fmt);
for ($i=0; $i < $len; $i++) {
if ($s) $s .= '+';
$ch = $fmt[$i];
switch($ch) {
case 'Y':
case 'y':
$s .= "datename(yyyy,$col)";
break;
case 'M':
$s .= "convert(char(3),$col,0)";
break;
case 'm':
$s .= "replace(str(month($col),2),' ','0')";
break;
case 'Q':
case 'q':
$s .= "datename(quarter,$col)";
break;
case 'D':
case 'd':
$s .= "replace(str(day($col),2),' ','0')";
break;
case 'h':
$s .= "substring(convert(char(14),$col,0),13,2)";
break;
case 'H':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
break;
case 'i':
$s .= "replace(str(datepart(mi,$col),2),' ','0')";
break;
case 's':
$s .= "replace(str(datepart(ss,$col),2),' ','0')";
break;
case 'a':
case 'A':
$s .= "substring(convert(char(19),$col,0),18,2)";
break;
default:
if ($ch == '\\') {
$i++;
$ch = substr($fmt,$i,1);
}
$s .= $this->qstr($ch);
break;
}
}
return $s;
}
}
class ADORecordSet_odbc_mssql extends ADORecordSet_odbc {
var $databaseType = 'odbc_mssql';
function ADORecordSet_odbc_mssql($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}
?>
+111 -111
View File
@@ -1,112 +1,112 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Oracle support via ODBC. Requires ODBC. Works on Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
class ADODB_odbc_oracle extends ADODB_odbc {
var $databaseType = 'odbc_oracle';
var $replaceQuote = "''"; // string to use to replace quotes
var $concat_operator='||';
var $fmtDate = "'Y-m-d 00:00:00'";
var $fmtTimeStamp = "'Y-m-d h:i:sA'";
var $metaTablesSQL = 'select table_name from cat';
var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
var $sysDate = "TRUNC(SYSDATE)";
var $sysTimeStamp = 'SYSDATE';
//var $_bindInputArray = false;
function ADODB_odbc_oracle()
{
$this->ADODB_odbc();
}
function &MetaTables()
{
if ($this->metaTablesSQL) {
$rs = $this->Execute($this->metaTablesSQL);
if ($rs === false) return false;
$arr = $rs->GetArray();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
$arr2[] = $arr[$i][0];
}
$rs->Close();
return $arr2;
}
return false;
}
function &MetaColumns($table)
{
if (!empty($this->metaColumnsSQL)) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF) { //print_r($rs->fields);
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
// returns true or false
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
$php_errormsg = '';
$this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
$this->_errorMsg = $php_errormsg;
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
//if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
return $this->_connectionID != false;
}
// returns true or false
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
$php_errormsg = '';
$this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
$this->_errorMsg = $php_errormsg;
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
//if ($this->_connectionID) odbc_autocommit($this->_connectionID,true);
return $this->_connectionID != false;
}
}
class ADORecordSet_odbc_oracle extends ADORecordSet_odbc {
var $databaseType = 'odbc_oracle';
function ADORecordSet_odbc_oracle($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Oracle support via ODBC. Requires ODBC. Works on Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
class ADODB_odbc_oracle extends ADODB_odbc {
var $databaseType = 'odbc_oracle';
var $replaceQuote = "''"; /* string to use to replace quotes */
var $concat_operator='||';
var $fmtDate = "'Y-m-d 00:00:00'";
var $fmtTimeStamp = "'Y-m-d h:i:sA'";
var $metaTablesSQL = 'select table_name from cat';
var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
var $sysDate = "TRUNC(SYSDATE)";
var $sysTimeStamp = 'SYSDATE';
/* var $_bindInputArray = false; */
function ADODB_odbc_oracle()
{
$this->ADODB_odbc();
}
function &MetaTables()
{
if ($this->metaTablesSQL) {
$rs = $this->Execute($this->metaTablesSQL);
if ($rs === false) return false;
$arr = $rs->GetArray();
$arr2 = array();
for ($i=0; $i < sizeof($arr); $i++) {
$arr2[] = $arr[$i][0];
}
$rs->Close();
return $arr2;
}
return false;
}
function &MetaColumns($table)
{
if (!empty($this->metaColumnsSQL)) {
$rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table)));
if ($rs === false) return false;
$retarr = array();
while (!$rs->EOF) { /* print_r($rs->fields); */
$fld = new ADOFieldObject();
$fld->name = $rs->fields[0];
$fld->type = $rs->fields[1];
$fld->max_length = $rs->fields[2];
$retarr[strtoupper($fld->name)] = $fld;
$rs->MoveNext();
}
$rs->Close();
return $retarr;
}
return false;
}
/* returns true or false */
function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
$php_errormsg = '';
$this->_connectionID = odbc_connect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
$this->_errorMsg = $php_errormsg;
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
/* if ($this->_connectionID) odbc_autocommit($this->_connectionID,true); */
return $this->_connectionID != false;
}
/* returns true or false */
function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
{
global $php_errormsg;
$php_errormsg = '';
$this->_connectionID = odbc_pconnect($argDSN,$argUsername,$argPassword,SQL_CUR_USE_ODBC );
$this->_errorMsg = $php_errormsg;
$this->Execute("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD HH24:MI:SS'");
/* if ($this->_connectionID) odbc_autocommit($this->_connectionID,true); */
return $this->_connectionID != false;
}
}
class ADORecordSet_odbc_oracle extends ADORecordSet_odbc {
var $databaseType = 'odbc_oracle';
function ADORecordSet_odbc_oracle($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
}
?>
+267 -267
View File
@@ -1,268 +1,268 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Latest version is available at http://php.weblogs.com/
Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.
If you are using Oracle 8, use the oci8 driver which is much better and more reliable.
*/
// select table_name from cat -- MetaTables
//
class ADODB_oracle extends ADOConnection {
var $databaseType = "oracle";
var $replaceQuote = "\'"; // string to use to replace quotes
var $concat_operator='||';
var $_curs;
var $_initdate = true; // init date to YYYY-MM-DD
var $metaTablesSQL = 'select table_name from cat';
var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";
var $sysTimeStamp = 'SYSDATE';
function ADODB_oracle()
{
}
// format and return date string in database date format
function DBDate($d)
{
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";
}
// format and return date string in database timestamp format
function DBTimeStamp($ts)
{
if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);
return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
}
function BeginTrans()
{
$this->autoCommit = false;
ora_commitoff($this->_connectionID);
return true;
}
function CommitTrans($ok=true)
{
if (!$ok) return $this->RollbackTrans();
$ret = ora_commit($this->_connectionID);
ora_commiton($this->_connectionID);
return $ret;
}
function RollbackTrans()
{
$ret = ora_rollback($this->_connectionID);
ora_commiton($this->_connectionID);
return $ret;
}
/* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */
function ErrorMsg()
{
$this->_errorMsg = @ora_error($this->_curs);
if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);
return $this->_errorMsg;
}
function ErrorNo()
{
$err = @ora_errorcode($this->_curs);
if (!$err) return @ora_errorcode($this->_connectionID);
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if ($argHostname) putenv("ORACLE_HOME=$argHostname");
if ($argDatabasename) $argUsername .= "@$argDatabasename";
//if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>";
$this->_connectionID = ora_logon($argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoCommit) ora_commiton($this->_connectionID);
if ($this->_initdate) {
$rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
if ($rs) ora_close($rs);
}
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if ($argHostname) putenv("ORACLE_HOME=$argHostname");
if ($argDatabasename) $argUsername .= "@$argDatabasename";
//if ($argHostname) print "<p>PConnect: 1st argument should be left blank for $this->databaseType</p>";
$this->_connectionID = ora_plogon($argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoCommit) ora_commiton($this->_connectionID);
if ($this->autoRollback) ora_rollback($this->_connectionID);
if ($this->_initdate) {
$rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
if ($rs) ora_close($rs);
}
return true;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr=false)
{
$curs = ora_open($this->_connectionID);
if ($curs === false) return false;
$this->_curs = $curs;
if (!ora_parse($curs,$sql)) return false;
if (ora_exec($curs)) return $curs;
@ora_close($curs);
return false;
}
// returns true or false
function _close()
{
return @ora_close($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_oracle extends ADORecordSet {
var $databaseType = "oracle";
var $bind = false;
function ADORecordset_oracle($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
$this->_queryID = $queryID;
$this->_inited = true;
$this->fields = array();
if ($queryID) {
$this->_currentRow = 0;
$this->EOF = !$this->_fetch();
@$this->_initrs();
} else {
$this->_numOfRows = 0;
$this->_numOfFields = 0;
$this->EOF = true;
}
return $this->_queryID;
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fld->name = ora_columnname($this->_queryID, $fieldOffset);
$fld->type = ora_columntype($this->_queryID, $fieldOffset);
$fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);
return $fld;
}
/* Use associative array to get fields array */
function Fields($colname)
{
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _initrs()
{
$this->_numOfRows = -1;
$this->_numOfFields = @ora_numcols($this->_queryID);
}
function _seek($row)
{
return false;
}
function _fetch($ignore_fields=false) {
// should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1
if ($this->fetchMode & ADODB_FETCH_ASSOC)
return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
else
return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
return @ora_close($this->_queryID);
}
function MetaType($t,$len=-1)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'VARCHAR':
case 'VARCHAR2':
case 'CHAR':
case 'VARBINARY':
case 'BINARY':
if ($len <= $this->blobSize) return 'C';
case 'LONG':
case 'LONG VARCHAR':
case 'CLOB':
return 'X';
case 'LONG RAW':
case 'LONG VARBINARY':
case 'BLOB':
return 'B';
case 'DATE': return 'D';
//case 'T': return 'T';
case 'BIT': return 'L';
case 'INT':
case 'SMALLINT':
case 'INTEGER': return 'I';
default: return 'N';
}
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Latest version is available at http://php.weblogs.com/
Oracle data driver. Requires Oracle client. Works on Windows and Unix and Oracle 7 and 8.
If you are using Oracle 8, use the oci8 driver which is much better and more reliable.
*/
/* select table_name from cat -- MetaTables */
/* */
class ADODB_oracle extends ADOConnection {
var $databaseType = "oracle";
var $replaceQuote = "''"; /* string to use to replace quotes */
var $concat_operator='||';
var $_curs;
var $_initdate = true; /* init date to YYYY-MM-DD */
var $metaTablesSQL = 'select table_name from cat';
var $metaColumnsSQL = "select cname,coltype,width from col where tname='%s' order by colno";
var $sysDate = "TO_DATE(TO_CHAR(SYSDATE,'YYYY-MM-DD'),'YYYY-MM-DD')";
var $sysTimeStamp = 'SYSDATE';
function ADODB_oracle()
{
}
/* format and return date string in database date format */
function DBDate($d)
{
if (is_string($d)) $d = ADORecordSet::UnixDate($d);
return 'TO_DATE('.adodb_date($this->fmtDate,$d).",'YYYY-MM-DD')";
}
/* format and return date string in database timestamp format */
function DBTimeStamp($ts)
{
if (is_string($ts)) $d = ADORecordSet::UnixTimeStamp($ts);
return 'TO_DATE('.adodb_date($this->fmtTimeStamp,$ts).",'RRRR-MM-DD, HH:MI:SS AM')";
}
function BeginTrans()
{
$this->autoCommit = false;
ora_commitoff($this->_connectionID);
return true;
}
function CommitTrans($ok=true)
{
if (!$ok) return $this->RollbackTrans();
$ret = ora_commit($this->_connectionID);
ora_commiton($this->_connectionID);
return $ret;
}
function RollbackTrans()
{
$ret = ora_rollback($this->_connectionID);
ora_commiton($this->_connectionID);
return $ret;
}
/* there seems to be a bug in the oracle extension -- always returns ORA-00000 - no error */
function ErrorMsg()
{
$this->_errorMsg = @ora_error($this->_curs);
if (!$this->_errorMsg) $this->_errorMsg = @ora_error($this->_connectionID);
return $this->_errorMsg;
}
function ErrorNo()
{
$err = @ora_errorcode($this->_curs);
if (!$err) return @ora_errorcode($this->_connectionID);
}
/* returns true or false */
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if ($argHostname) putenv("ORACLE_HOME=$argHostname");
if ($argDatabasename) $argUsername .= "@$argDatabasename";
/* if ($argHostname) print "<p>Connect: 1st argument should be left blank for $this->databaseType</p>"; */
$this->_connectionID = ora_logon($argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoCommit) ora_commiton($this->_connectionID);
if ($this->_initdate) {
$rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
if ($rs) ora_close($rs);
}
return true;
}
/* returns true or false */
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
if ($argHostname) putenv("ORACLE_HOME=$argHostname");
if ($argDatabasename) $argUsername .= "@$argDatabasename";
/* if ($argHostname) print "<p>PConnect: 1st argument should be left blank for $this->databaseType</p>"; */
$this->_connectionID = ora_plogon($argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($this->autoCommit) ora_commiton($this->_connectionID);
if ($this->autoRollback) ora_rollback($this->_connectionID);
if ($this->_initdate) {
$rs = $this->_query("ALTER SESSION SET NLS_DATE_FORMAT='YYYY-MM-DD'");
if ($rs) ora_close($rs);
}
return true;
}
/* returns query ID if successful, otherwise false */
function _query($sql,$inputarr=false)
{
$curs = ora_open($this->_connectionID);
if ($curs === false) return false;
$this->_curs = $curs;
if (!ora_parse($curs,$sql)) return false;
if (ora_exec($curs)) return $curs;
@ora_close($curs);
return false;
}
/* returns true or false */
function _close()
{
return @ora_logoff($this->_connectionID);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordset_oracle extends ADORecordSet {
var $databaseType = "oracle";
var $bind = false;
function ADORecordset_oracle($queryID,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
$this->fetchMode = $mode;
$this->_queryID = $queryID;
$this->_inited = true;
$this->fields = array();
if ($queryID) {
$this->_currentRow = 0;
$this->EOF = !$this->_fetch();
@$this->_initrs();
} else {
$this->_numOfRows = 0;
$this->_numOfFields = 0;
$this->EOF = true;
}
return $this->_queryID;
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function FetchField($fieldOffset = -1)
{
$fld = new ADOFieldObject;
$fld->name = ora_columnname($this->_queryID, $fieldOffset);
$fld->type = ora_columntype($this->_queryID, $fieldOffset);
$fld->max_length = ora_columnsize($this->_queryID, $fieldOffset);
return $fld;
}
/* Use associative array to get fields array */
function Fields($colname)
{
if (!$this->bind) {
$this->bind = array();
for ($i=0; $i < $this->_numOfFields; $i++) {
$o = $this->FetchField($i);
$this->bind[strtoupper($o->name)] = $i;
}
}
return $this->fields[$this->bind[strtoupper($colname)]];
}
function _initrs()
{
$this->_numOfRows = -1;
$this->_numOfFields = @ora_numcols($this->_queryID);
}
function _seek($row)
{
return false;
}
function _fetch($ignore_fields=false) {
/* should remove call by reference, but ora_fetch_into requires it in 4.0.3pl1 */
if ($this->fetchMode & ADODB_FETCH_ASSOC)
return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS|ORA_FETCHINTO_ASSOC);
else
return @ora_fetch_into($this->_queryID,&$this->fields,ORA_FETCHINTO_NULLS);
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close()
{
return @ora_close($this->_queryID);
}
function MetaType($t,$len=-1)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'VARCHAR':
case 'VARCHAR2':
case 'CHAR':
case 'VARBINARY':
case 'BINARY':
if ($len <= $this->blobSize) return 'C';
case 'LONG':
case 'LONG VARCHAR':
case 'CLOB':
return 'X';
case 'LONG RAW':
case 'LONG VARBINARY':
case 'BLOB':
return 'B';
case 'DATE': return 'D';
/* case 'T': return 'T'; */
case 'BIT': return 'L';
case 'INT':
case 'SMALLINT':
case 'INTEGER': return 'I';
default: return 'N';
}
}
}
?>
+13 -13
View File
@@ -1,14 +1,14 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
remapped to "postgres7". Maintaining multiple postgres drivers is no easy
job, so hopefully this will ensure greater consistency and fewer bugs.
*/
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
NOTE: Since 3.31, this file is no longer used, and the "postgres" driver is
remapped to "postgres7". Maintaining multiple postgres drivers is no easy
job, so hopefully this will ensure greater consistency and fewer bugs.
*/
?>
File diff suppressed because it is too large Load Diff
+73 -73
View File
@@ -1,74 +1,74 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Postgres7 support.
28 Feb 2001: Currently indicate that we support LIMIT
01 Dec 2001: dannym added support for default values
*/
include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
class ADODB_postgres7 extends ADODB_postgres64 {
var $databaseType = 'postgres7';
var $hasLimit = true; // set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10
var $ansiOuter = true;
function ADODB_postgres7()
{
$this->ADODB_postgres64();
}
// the following should be compat with postgresql 7.2,
// which makes obsolete the LIMIT limit,offset syntax
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$arg3=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : '';
return $secs2cache ?
$this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr,$arg3)
:
$this->Execute($sql."$limitStr$offsetStr",$inputarr,$arg3);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
var $databaseType = "postgres7";
function ADORecordSet_postgres7($queryID,$mode=false)
{
$this->ADORecordSet_postgres64($queryID,$mode);
}
// 10% speedup to move MoveNext to child class
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if (is_array($this->fields)) {
if (isset($this->_blobArr)) $this->_fixblobs();
return true;
}
}
$this->fields = false;
$this->EOF = true;
}
return false;
}
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Postgres7 support.
28 Feb 2001: Currently indicate that we support LIMIT
01 Dec 2001: dannym added support for default values
*/
include_once(ADODB_DIR."/drivers/adodb-postgres64.inc.php");
class ADODB_postgres7 extends ADODB_postgres64 {
var $databaseType = 'postgres7';
var $hasLimit = true; /* set to true for pgsql 6.5+ only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 */
var $ansiOuter = true;
function ADODB_postgres7()
{
$this->ADODB_postgres64();
}
/* the following should be compat with postgresql 7.2, */
/* which makes obsolete the LIMIT limit,offset syntax */
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$arg3=false,$secs2cache=0)
{
$offsetStr = ($offset >= 0) ? " OFFSET $offset" : '';
$limitStr = ($nrows >= 0) ? " LIMIT $nrows" : '';
return $secs2cache ?
$this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr,$arg3)
:
$this->Execute($sql."$limitStr$offsetStr",$inputarr,$arg3);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
class ADORecordSet_postgres7 extends ADORecordSet_postgres64{
var $databaseType = "postgres7";
function ADORecordSet_postgres7($queryID,$mode=false)
{
$this->ADORecordSet_postgres64($queryID,$mode);
}
/* 10% speedup to move MoveNext to child class */
function MoveNext()
{
if (!$this->EOF) {
$this->_currentRow++;
if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) {
$this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode);
if (is_array($this->fields)) {
if (isset($this->_blobArr)) $this->_fixblobs();
return true;
}
}
$this->fields = false;
$this->EOF = true;
}
return false;
}
}
?>
+29 -29
View File
@@ -1,30 +1,30 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Synonym for csv driver.
*/
if (! defined("_ADODB_PROXY_LAYER")) {
define("_ADODB_PROXY_LAYER", 1 );
include(ADODB_DIR."/drivers/adodb-csv.inc.php");
class ADODB_proxy extends ADODB_csv {
var $databaseType = 'proxy';
var $databaseProvider = 'csv';
}
class ADORecordset_proxy extends ADORecordset_csv {
var $databaseType = "proxy";
function ADORecordset_proxy($id,$mode=false)
{
$this->ADORecordset($id,$mode);
}
};
} // define
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4.
Synonym for csv driver.
*/
if (! defined("_ADODB_PROXY_LAYER")) {
define("_ADODB_PROXY_LAYER", 1 );
include(ADODB_DIR."/drivers/adodb-csv.inc.php");
class ADODB_proxy extends ADODB_csv {
var $databaseType = 'proxy';
var $databaseProvider = 'csv';
}
class ADORecordset_proxy extends ADORecordset_csv {
var $databaseType = "proxy";
function ADORecordset_proxy($id,$mode=false)
{
$this->ADORecordset($id,$mode);
}
};
} /* define */
?>
+166 -166
View File
@@ -1,166 +1,166 @@
<?php
/*
version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights
reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
21.02.2002 - Wade Johnson [email protected]
Extended ODBC class for Sybase SQLAnywhere.
1) Added support to retrieve the last row insert ID on tables with
primary key column using autoincrement function.
2) Added blob support. Usage:
a) create blob variable on db server:
$dbconn->create_blobvar($blobVarName);
b) load blob var from file. $filename must be complete path
$dbcon->load_blobvar_from_file($blobVarName, $filename);
c) Use the $blobVarName in SQL insert or update statement in the values
clause:
$recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '
.
'VALUES (\'test\', ' . $blobVarName . ')');
instead of loading blob from a file, you can also load from
an unformatted (raw) blob variable:
$dbcon->load_blobvar_from_var($blobVarName, $varName);
d) drop blob variable on db server to free up resources:
$dbconn->drop_blobvar($blobVarName);
Sybase_SQLAnywhere data driver. Requires ODBC.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_SYBASE_SQLANYWHERE')){
define('ADODB_SYBASE_SQLANYWHERE',1);
class ADODB_sqlanywhere extends ADODB_odbc {
var $databaseType = "sqlanywhere";
var $hasInsertID = true;
function ADODB_sqlanywhere()
{
$this->ADODB_odbc();
}
function _insertid() {
return $this->GetOne('select @@identity');
}
function create_blobvar($blobVarName) {
$this->Execute("create variable $blobVarName long binary");
return;
}
function drop_blobvar($blobVarName) {
$this->Execute("drop variable $blobVarName");
return;
}
function load_blobvar_from_file($blobVarName, $filename) {
$chunk_size = 1000;
$fd = fopen ($filename, "rb");
$integer_chunks = (integer)filesize($filename) / $chunk_size;
$modulus = filesize($filename) % $chunk_size;
if ($modulus != 0){
$integer_chunks += 1;
}
for($loop=1;$loop<=$integer_chunks;$loop++){
$contents = fread ($fd, $chunk_size);
$contents = bin2hex($contents);
$hexstring = '';
for($loop2=0;$loop2<strlen($contents);$loop2+=2){
$hexstring .= '\x' . substr($contents,$loop2,2);
}
$hexstring = $this->qstr($hexstring);
$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
}
fclose ($fd);
return;
}
function load_blobvar_from_var($blobVarName, &$varName) {
$chunk_size = 1000;
$integer_chunks = (integer)strlen($varName) / $chunk_size;
$modulus = strlen($varName) % $chunk_size;
if ($modulus != 0){
$integer_chunks += 1;
}
for($loop=1;$loop<=$integer_chunks;$loop++){
$contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);
$contents = bin2hex($contents);
$hexstring = '';
for($loop2=0;$loop2<strlen($contents);$loop2+=2){
$hexstring .= '\x' . substr($contents,$loop2,2);
}
$hexstring = $this->qstr($hexstring);
$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
}
return;
}
/*
Insert a null into the blob field of the table first.
Then use UpdateBlob to store the blob.
Usage:
$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')
{
$blobVarName = 'hold_blob';
$this->create_blobvar($blobVarName);
$this->load_blobvar_from_var($blobVarName, $val);
$this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");
$this->drop_blobvar($blobVarName);
return true;
}
}; //class
class ADORecordSet_sqlanywhere extends ADORecordSet_odbc {
var $databaseType = "sqlanywhere";
function ADORecordSet_sqlanywhere($id,$mode=false)
{
$this->ADORecordSet_odbc($id,$mode);
}
}; //class
} //define
?>
<?php
/*
version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights
reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
21.02.2002 - Wade Johnson [email protected]
Extended ODBC class for Sybase SQLAnywhere.
1) Added support to retrieve the last row insert ID on tables with
primary key column using autoincrement function.
2) Added blob support. Usage:
a) create blob variable on db server:
$dbconn->create_blobvar($blobVarName);
b) load blob var from file. $filename must be complete path
$dbcon->load_blobvar_from_file($blobVarName, $filename);
c) Use the $blobVarName in SQL insert or update statement in the values
clause:
$recordSet = $dbconn->Execute('INSERT INTO tabname (idcol, blobcol) '
.
'VALUES (\'test\', ' . $blobVarName . ')');
instead of loading blob from a file, you can also load from
an unformatted (raw) blob variable:
$dbcon->load_blobvar_from_var($blobVarName, $varName);
d) drop blob variable on db server to free up resources:
$dbconn->drop_blobvar($blobVarName);
Sybase_SQLAnywhere data driver. Requires ODBC.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_SYBASE_SQLANYWHERE')){
define('ADODB_SYBASE_SQLANYWHERE',1);
class ADODB_sqlanywhere extends ADODB_odbc {
var $databaseType = "sqlanywhere";
var $hasInsertID = true;
function ADODB_sqlanywhere()
{
$this->ADODB_odbc();
}
function _insertid() {
return $this->GetOne('select @@identity');
}
function create_blobvar($blobVarName) {
$this->Execute("create variable $blobVarName long binary");
return;
}
function drop_blobvar($blobVarName) {
$this->Execute("drop variable $blobVarName");
return;
}
function load_blobvar_from_file($blobVarName, $filename) {
$chunk_size = 1000;
$fd = fopen ($filename, "rb");
$integer_chunks = (integer)filesize($filename) / $chunk_size;
$modulus = filesize($filename) % $chunk_size;
if ($modulus != 0){
$integer_chunks += 1;
}
for($loop=1;$loop<=$integer_chunks;$loop++){
$contents = fread ($fd, $chunk_size);
$contents = bin2hex($contents);
$hexstring = '';
for($loop2=0;$loop2<strlen($contents);$loop2+=2){
$hexstring .= '\x' . substr($contents,$loop2,2);
}
$hexstring = $this->qstr($hexstring);
$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
}
fclose ($fd);
return;
}
function load_blobvar_from_var($blobVarName, &$varName) {
$chunk_size = 1000;
$integer_chunks = (integer)strlen($varName) / $chunk_size;
$modulus = strlen($varName) % $chunk_size;
if ($modulus != 0){
$integer_chunks += 1;
}
for($loop=1;$loop<=$integer_chunks;$loop++){
$contents = substr ($varName, (($loop - 1) * $chunk_size), $chunk_size);
$contents = bin2hex($contents);
$hexstring = '';
for($loop2=0;$loop2<strlen($contents);$loop2+=2){
$hexstring .= '\x' . substr($contents,$loop2,2);
}
$hexstring = $this->qstr($hexstring);
$this->Execute("set $blobVarName = $blobVarName || " . $hexstring);
}
return;
}
/*
Insert a null into the blob field of the table first.
Then use UpdateBlob to store the blob.
Usage:
$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')
{
$blobVarName = 'hold_blob';
$this->create_blobvar($blobVarName);
$this->load_blobvar_from_var($blobVarName, $val);
$this->Execute("UPDATE $table SET $column=$blobVarName WHERE $where");
$this->drop_blobvar($blobVarName);
return true;
}
}; /* class */
class ADORecordSet_sqlanywhere extends ADORecordSet_odbc {
var $databaseType = "sqlanywhere";
function ADORecordSet_sqlanywhere($id,$mode=false)
{
$this->ADORecordSet_odbc($id,$mode);
}
}; /* class */
} /* define */
?>
+316 -316
View File
@@ -1,316 +1,316 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Sybase driver contributed by Toni ([email protected])
- MSSQL date patch applied.
Date patch by Toni 15 Feb 2002
*/
class ADODB_sybase extends ADOConnection {
var $databaseType = "sybase";
var $dataProvider = 'sybase';
var $replaceQuote = "''"; // string to use to replace quotes
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";
var $metaColumnsSQL = "SELECT c.name,t.name,c.length FROM syscolumns c, systypes t, sysobjects o WHERE o.name='%s' and t.xusertype=c.xusertype and o.id=c.id";
/*
"select c.name,t.name,c.length from
syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id
where o.name='%s'";
*/
var $concat_operator = '+';
var $sysDate = 'GetDate()';
var $arrayClass = 'ADORecordSet_array_sybase';
var $sysDate = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
function ADODB_sybase()
{
}
// might require begintrans -- committrans
function _insertid()
{
return $this->GetOne('select @@identity');
}
// might require begintrans -- committrans
function _affectedrows()
{
return $this->GetOne('select @@rowcount');
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('BEGIN TRAN');
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
$this->transCnt -= 1;
$this->Execute('COMMIT TRAN');
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
$this->transCnt -= 1;
$this->Execute('ROLLBACK TRAN');
return true;
}
// http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4
function RowLock($tables,$where)
{
if (!$this->_hastrans) $this->BeginTrans();
$tables = str_replace(',',' HOLDLOCK,',$tables);
return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");
}
function SelectDB($dbName) {
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @sybase_select_db($dbName);
}
else return false;
}
/* Returns: the last error message from previous database operation
Note: This function is NOT available for Microsoft SQL Server. */
function ErrorMsg() {
$this->_errorMsg = sybase_get_last_message();
return $this->_errorMsg;
}
// returns true or false
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns true or false
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
// returns query ID if successful, otherwise false
function _query($sql,$inputarr)
{
global $ADODB_COUNTRECS;
if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
return sybase_unbuffered_query($sql,$this->_connectionID);
else
return sybase_query($sql,$this->_connectionID);
}
// See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$arg3=false,$secs2cache=0)
{
if ($secs2cache > 0) // we do not cache rowcount, so we have to load entire recordset
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
$cnt = ($nrows > 0) ? $nrows : 0;
if ($offset > 0 && $cnt) $cnt += $offset;
$this->Execute("set rowcount $cnt");
$rs = &ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
$this->Execute("set rowcount 0");
return $rs;
}
// returns true or false
function _close()
{
return @sybase_close($this->_connectionID);
}
function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
global $ADODB_sybase_mths;
$ADODB_sybase_mths = array(
'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
class ADORecordset_sybase extends ADORecordSet {
var $databaseType = "sybase";
var $canSeek = true;
// _mths works only in non-localised system
var $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
function ADORecordset_sybase($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
else $this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function &FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @sybase_fetch_field($this->_queryID, $fieldOffset);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @sybase_fetch_field($this->_queryID);
}
// older versions of PHP did not support type, only numeric
if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';
return $o;
}
function _initrs()
{
global $ADODB_COUNTRECS;
$this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;
$this->_numOfFields = @sybase_num_fields($this->_queryID);
}
function _seek($row)
{
return @sybase_data_seek($this->_queryID, $row);
}
function _fetch($ignore_fields=false)
{
if ($this->fetchMode == ADODB_FETCH_NUM) {
$this->fields = @sybase_fetch_row($this->_queryID);
} else if ($this->fetchMode == ADODB_FETCH_ASSOC) {
$this->fields = @sybase_fetch_row($this->_queryID);
if (is_array($this->fields)) {
$this->fields = $this->GetRowAssoc(ADODB_CASE_ASSOC);
return true;
}
return false;
} else {
$this->fields = @sybase_fetch_array($this->_queryID);
}
if ( is_array($this->fields)) {
return true;
}
return false;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close() {
return @sybase_free_result($this->_queryID);
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
}
class ADORecordSet_array_sybase extends ADORecordSet_array {
function ADORecordSet_array_sybase($id=-1)
{
$this->ADORecordSet_array($id);
}
// sybase/mssql uses a default date like Dec 30 2000 12:00AM
function UnixDate($v)
{
global $ADODB_sybase_mths;
//Dec 30 2000 12:00AM
if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
,$v, $rr)) return parent::UnixDate($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$themth = substr(strtoupper($rr[1]),0,3);
$themth = $ADODB_sybase_mths[$themth];
if ($themth <= 0) return false;
// h-m-s-MM-DD-YY
return mktime(0,0,0,$themth,$rr[2],$rr[3]);
}
function UnixTimeStamp($v)
{
global $ADODB_sybase_mths;
//11.02.2001 Toni Tunkkari [email protected]
//Changed [0-9] to [0-9 ] in day conversion
if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$themth = substr(strtoupper($rr[1]),0,3);
$themth = $ADODB_sybase_mths[$themth];
if ($themth <= 0) return false;
switch (strtoupper($rr[6])) {
case 'P':
if ($rr[4]<12) $rr[4] += 12;
break;
case 'A':
if ($rr[4]==12) $rr[4] = 0;
break;
default:
break;
}
// h-m-s-MM-DD-YY
return mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);
}
}
?>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim. All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Sybase driver contributed by Toni ([email protected])
- MSSQL date patch applied.
Date patch by Toni 15 Feb 2002
*/
class ADODB_sybase extends ADOConnection {
var $databaseType = "sybase";
/* var $dataProvider = 'sybase'; */
var $replaceQuote = "''"; /* string to use to replace quotes */
var $fmtDate = "'Y-m-d'";
var $fmtTimeStamp = "'Y-m-d H:i:s'";
var $hasInsertID = true;
var $hasAffectedRows = true;
var $metaTablesSQL="select name from sysobjects where type='U' or type='V'";
var $metaColumnsSQL = "SELECT c.name,t.name,c.length FROM syscolumns c, systypes t, sysobjects o WHERE o.name='%s' and t.xusertype=c.xusertype and o.id=c.id";
/*
"select c.name,t.name,c.length from
syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id
where o.name='%s'";
*/
var $concat_operator = '+';
var $sysDate = 'GetDate()';
var $arrayClass = 'ADORecordSet_array_sybase';
var $sysDate = 'GetDate()';
var $leftOuter = '*=';
var $rightOuter = '=*';
function ADODB_sybase()
{
}
/* might require begintrans -- committrans */
function _insertid()
{
return $this->GetOne('select @@identity');
}
/* might require begintrans -- committrans */
function _affectedrows()
{
return $this->GetOne('select @@rowcount');
}
function BeginTrans()
{
if ($this->transOff) return true;
$this->transCnt += 1;
$this->Execute('BEGIN TRAN');
return true;
}
function CommitTrans($ok=true)
{
if ($this->transOff) return true;
if (!$ok) return $this->RollbackTrans();
$this->transCnt -= 1;
$this->Execute('COMMIT TRAN');
return true;
}
function RollbackTrans()
{
if ($this->transOff) return true;
$this->transCnt -= 1;
$this->Execute('ROLLBACK TRAN');
return true;
}
/* http://www.isug.com/Sybase_FAQ/ASE/section6.1.html#6.1.4 */
function RowLock($tables,$where)
{
if (!$this->_hastrans) $this->BeginTrans();
$tables = str_replace(',',' HOLDLOCK,',$tables);
return $this->GetOne("select top 1 null as ignore from $tables HOLDLOCK where $where");
}
function SelectDB($dbName) {
$this->databaseName = $dbName;
if ($this->_connectionID) {
return @sybase_select_db($dbName);
}
else return false;
}
/* Returns: the last error message from previous database operation
Note: This function is NOT available for Microsoft SQL Server. */
function ErrorMsg() {
$this->_errorMsg = sybase_get_last_message();
return $this->_errorMsg;
}
/* returns true or false */
function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = sybase_connect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/* returns true or false */
function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
{
$this->_connectionID = sybase_pconnect($argHostname,$argUsername,$argPassword);
if ($this->_connectionID === false) return false;
if ($argDatabasename) return $this->SelectDB($argDatabasename);
return true;
}
/* returns query ID if successful, otherwise false */
function _query($sql,$inputarr)
{
global $ADODB_COUNTRECS;
if ($ADODB_COUNTRECS == false && ADODB_PHPVER >= 0x4300)
return sybase_unbuffered_query($sql,$this->_connectionID);
else
return sybase_query($sql,$this->_connectionID);
}
/* See http://www.isug.com/Sybase_FAQ/ASE/section6.2.html#6.2.12 */
function &SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$arg3=false,$secs2cache=0)
{
if ($secs2cache > 0) /* we do not cache rowcount, so we have to load entire recordset */
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
$cnt = ($nrows > 0) ? $nrows : 0;
if ($offset > 0 && $cnt) $cnt += $offset;
$this->Execute("set rowcount $cnt");
$rs = &ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
$this->Execute("set rowcount 0");
return $rs;
}
/* returns true or false */
function _close()
{
return @sybase_close($this->_connectionID);
}
function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
}
/*--------------------------------------------------------------------------------------
Class Name: Recordset
--------------------------------------------------------------------------------------*/
global $ADODB_sybase_mths;
$ADODB_sybase_mths = array(
'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
class ADORecordset_sybase extends ADORecordSet {
var $databaseType = "sybase";
var $canSeek = true;
/* _mths works only in non-localised system */
var $_mths = array('JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
function ADORecordset_sybase($id,$mode=false)
{
if ($mode === false) {
global $ADODB_FETCH_MODE;
$mode = $ADODB_FETCH_MODE;
}
if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC;
else $this->fetchMode = $mode;
return $this->ADORecordSet($id,$mode);
}
/* Returns: an object containing field information.
Get column information in the Recordset object. fetchField() can be used in order to obtain information about
fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
fetchField() is retrieved. */
function &FetchField($fieldOffset = -1)
{
if ($fieldOffset != -1) {
$o = @sybase_fetch_field($this->_queryID, $fieldOffset);
}
else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
$o = @sybase_fetch_field($this->_queryID);
}
/* older versions of PHP did not support type, only numeric */
if ($o && !isset($o->type)) $o->type = ($o->numeric) ? 'float' : 'varchar';
return $o;
}
function _initrs()
{
global $ADODB_COUNTRECS;
$this->_numOfRows = ($ADODB_COUNTRECS)? @sybase_num_rows($this->_queryID):-1;
$this->_numOfFields = @sybase_num_fields($this->_queryID);
}
function _seek($row)
{
return @sybase_data_seek($this->_queryID, $row);
}
function _fetch($ignore_fields=false)
{
if ($this->fetchMode == ADODB_FETCH_NUM) {
$this->fields = @sybase_fetch_row($this->_queryID);
} else if ($this->fetchMode == ADODB_FETCH_ASSOC) {
$this->fields = @sybase_fetch_row($this->_queryID);
if (is_array($this->fields)) {
$this->fields = $this->GetRowAssoc(ADODB_CASE_ASSOC);
return true;
}
return false;
} else {
$this->fields = @sybase_fetch_array($this->_queryID);
}
if ( is_array($this->fields)) {
return true;
}
return false;
}
/* close() only needs to be called if you are worried about using too much memory while your script
is running. All associated result memory for the specified result identifier will automatically be freed. */
function _close() {
return @sybase_free_result($this->_queryID);
}
/* sybase/mssql uses a default date like Dec 30 2000 12:00AM */
function UnixDate($v)
{
return ADORecordSet_array_sybase::UnixDate($v);
}
function UnixTimeStamp($v)
{
return ADORecordSet_array_sybase::UnixTimeStamp($v);
}
}
class ADORecordSet_array_sybase extends ADORecordSet_array {
function ADORecordSet_array_sybase($id=-1)
{
$this->ADORecordSet_array($id);
}
/* sybase/mssql uses a default date like Dec 30 2000 12:00AM */
function UnixDate($v)
{
global $ADODB_sybase_mths;
/* Dec 30 2000 12:00AM */
if (!ereg( "([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})"
,$v, $rr)) return parent::UnixDate($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$themth = substr(strtoupper($rr[1]),0,3);
$themth = $ADODB_sybase_mths[$themth];
if ($themth <= 0) return false;
/* h-m-s-MM-DD-YY */
return mktime(0,0,0,$themth,$rr[2],$rr[3]);
}
function UnixTimeStamp($v)
{
global $ADODB_sybase_mths;
/* 11.02.2001 Toni Tunkkari [email protected] */
/* Changed [0-9] to [0-9 ] in day conversion */
if (!ereg( "([A-Za-z]{3})[-/\. ]([0-9 ]{1,2})[-/\. ]([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})"
,$v, $rr)) return parent::UnixTimeStamp($v);
if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
$themth = substr(strtoupper($rr[1]),0,3);
$themth = $ADODB_sybase_mths[$themth];
if ($themth <= 0) return false;
switch (strtoupper($rr[6])) {
case 'P':
if ($rr[4]<12) $rr[4] += 12;
break;
case 'A':
if ($rr[4]==12) $rr[4] = 0;
break;
default:
break;
}
/* h-m-s-MM-DD-YY */
return mktime($rr[4],$rr[5],0,$themth,$rr[2],$rr[3]);
}
}
?>
+97 -97
View File
@@ -1,98 +1,98 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_VFP')){
define('ADODB_VFP',1);
class ADODB_vfp extends ADODB_odbc {
var $databaseType = "vfp";
var $fmtDate = "{^Y-m-d}";
var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
var $replaceQuote = "'+chr(39)+'" ;
var $true = '.T.';
var $false = '.F.';
var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
var $upperCase = 'upper';
var $_bindInputArray = false; // strangely enough, setting to true does not work reliably
var $sysTimeStamp = 'datetime()';
var $sysDate = 'date()';
var $ansiOuter = true;
var $hasTransactions = false;
var $curmode = SQL_CUR_USE_ODBC ; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
function ADODB_vfp()
{
$this->ADODB_odbc();
}
function BeginTrans() { return false;}
// quote string to be sent back to database
function qstr($s,$nofixquotes=false)
{
if (!$nofixquotes) return "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
return "'".$s."'";
}
// TOP requires ORDER BY for VFP
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)
{
if (!preg_match('/ORDER[ \t\r\n]+BY/i',$sql)) $sql .= ' ORDER BY 1';
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
}
};
class ADORecordSet_vfp extends ADORecordSet_odbc {
var $databaseType = "vfp";
function ADORecordSet_vfp($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
function MetaType($t,$len=-1)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'C':
if ($len <= $this->blobSize) return 'C';
case 'M':
return 'X';
case 'D': return 'D';
case 'T': return 'T';
case 'L': return 'L';
case 'I': return 'I';
default: return 'N';
}
}
}
} //define
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
Microsoft Visual FoxPro data driver. Requires ODBC. Works only on MS Windows.
*/
if (!defined('_ADODB_ODBC_LAYER')) {
include(ADODB_DIR."/drivers/adodb-odbc.inc.php");
}
if (!defined('ADODB_VFP')){
define('ADODB_VFP',1);
class ADODB_vfp extends ADODB_odbc {
var $databaseType = "vfp";
var $fmtDate = "{^Y-m-d}";
var $fmtTimeStamp = "{^Y-m-d, h:i:sA}";
var $replaceQuote = "'+chr(39)+'" ;
var $true = '.T.';
var $false = '.F.';
var $hasTop = 'top'; /* support mssql SELECT TOP 10 * FROM TABLE */
var $upperCase = 'upper';
var $_bindInputArray = false; /* strangely enough, setting to true does not work reliably */
var $sysTimeStamp = 'datetime()';
var $sysDate = 'date()';
var $ansiOuter = true;
var $hasTransactions = false;
var $curmode = SQL_CUR_USE_ODBC ; /* See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L */
function ADODB_vfp()
{
$this->ADODB_odbc();
}
function BeginTrans() { return false;}
/* quote string to be sent back to database */
function qstr($s,$nofixquotes=false)
{
if (!$nofixquotes) return "'".str_replace("\r\n","'+chr(13)+'",str_replace("'",$this->replaceQuote,$s))."'";
return "'".$s."'";
}
/* TOP requires ORDER BY for VFP */
function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$arg3=false,$secs2cache=0)
{
if (!preg_match('/ORDER[ \t\r\n]+BY/is',$sql)) $sql .= ' ORDER BY 1';
return ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$arg3,$secs2cache);
}
};
class ADORecordSet_vfp extends ADORecordSet_odbc {
var $databaseType = "vfp";
function ADORecordSet_vfp($id,$mode=false)
{
return $this->ADORecordSet_odbc($id,$mode);
}
function MetaType($t,$len=-1)
{
if (is_object($t)) {
$fieldobj = $t;
$t = $fieldobj->type;
$len = $fieldobj->max_length;
}
switch (strtoupper($t)) {
case 'C':
if ($len <= $this->blobSize) return 'C';
case 'M':
return 'X';
case 'D': return 'D';
case 'T': return 'T';
case 'L': return 'L';
case 'I': return 'I';
default: return 'N';
}
}
}
} /* define */
?>
+34
View File
@@ -0,0 +1,34 @@
<?php
$ADODB_LANG_ARRAY = array (
'LANG' => 'en',
DB_ERROR => 'unknown error',
DB_ERROR_ALREADY_EXISTS => 'already exists',
DB_ERROR_CANNOT_CREATE => 'can not create',
DB_ERROR_CANNOT_DELETE => 'can not delete',
DB_ERROR_CANNOT_DROP => 'can not drop',
DB_ERROR_CONSTRAINT => 'constraint violation',
DB_ERROR_DIVZERO => 'division by zero',
DB_ERROR_INVALID => 'invalid',
DB_ERROR_INVALID_DATE => 'invalid date or time',
DB_ERROR_INVALID_NUMBER => 'invalid number',
DB_ERROR_MISMATCH => 'mismatch',
DB_ERROR_NODBSELECTED => 'no database selected',
DB_ERROR_NOSUCHFIELD => 'no such field',
DB_ERROR_NOSUCHTABLE => 'no such table',
DB_ERROR_NOT_CAPABLE => 'DB backend not capable',
DB_ERROR_NOT_FOUND => 'not found',
DB_ERROR_NOT_LOCKED => 'not locked',
DB_ERROR_SYNTAX => 'syntax error',
DB_ERROR_UNSUPPORTED => 'not supported',
DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
DB_ERROR_INVALID_DSN => 'invalid DSN',
DB_ERROR_CONNECT_FAILED => 'connect failed',
0 => 'no error', /* DB_OK */
DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
DB_ERROR_NOSUCHDB => 'no such database',
DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions'
);
?>
+33
View File
@@ -0,0 +1,33 @@
<?php
$ADODB_LANG_ARRAY = array (
'LANG' => 'fr',
DB_ERROR => 'erreur inconnue',
DB_ERROR_ALREADY_EXISTS => 'existe d&eacute;j&agrave;',
DB_ERROR_CANNOT_CREATE => 'cr&eacute;tion impossible',
DB_ERROR_CANNOT_DELETE => 'effacement impossible',
DB_ERROR_CANNOT_DROP => 'suppression impossible',
DB_ERROR_CONSTRAINT => 'violation de contrainte',
DB_ERROR_DIVZERO => 'division par z&eacute;ro',
DB_ERROR_INVALID => 'invalide',
DB_ERROR_INVALID_DATE => 'date ou heure invalide',
DB_ERROR_INVALID_NUMBER => 'nombre invalide',
DB_ERROR_MISMATCH => 'erreur de concordance',
DB_ERROR_NODBSELECTED => 'pas de base de donn&eacute;ess&eacute;lectionn&eacute;e',
DB_ERROR_NOSUCHFIELD => 'nom de colonne invalide',
DB_ERROR_NOSUCHTABLE => 'table ou vue inexistante',
DB_ERROR_NOT_CAPABLE => 'fonction optionnelle non install&eacute;e',
DB_ERROR_NOT_FOUND => 'pas trouv&eacute;',
DB_ERROR_NOT_LOCKED => 'non verrouill&eacute;',
DB_ERROR_SYNTAX => 'erreur de syntaxe',
DB_ERROR_UNSUPPORTED => 'non support&eacute;',
DB_ERROR_VALUE_COUNT_ON_ROW => 'valeur ins&eacute;r&eacute;e trop grande pour colonne',
DB_ERROR_INVALID_DSN => 'DSN invalide',
DB_ERROR_CONNECT_FAILED => '&eacute;chec &agrave; la connexion',
0 => "pas d'erreur", /* DB_OK */
DB_ERROR_NEED_MORE_DATA => 'donn&eacute;es fournies insuffisantes',
DB_ERROR_EXTENSION_NOT_FOUND=> 'extension non trouv&eacute;e',
DB_ERROR_NOSUCHDB => 'base de donn&eacute;es inconnue',
DB_ERROR_ACCESS_VIOLATION => 'droits ynsuffisants'
);
?>
+162 -162
View File
@@ -1,163 +1,163 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Requires PHP4.01pl2 or later because it uses include_once
*/
/*
* Concept from [email protected].
*
* @param db Adodb database connection
* @param tables List of tables to join
* @rowfields List of fields to display on each row
* @colfield Pivot field to slice and display in columns, if we want to calculate
* ranges, we pass in an array (see example2)
* @where Where clause. Optional.
* @aggfield This is the field to sum. Optional.
* Since 2.3.1, if you can use your own aggregate function
* instead of SUM, eg. $sumfield = 'AVG(fieldname)';
* @sumlabel Prefix to display in sum columns. Optional.
* @aggfn Aggregate function to use (could be AVG, SUM, COUNT)
* @showcount Show count of records
*
* @returns Sql generated
*/
function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,
$aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)
{
if ($aggfield) $hidecnt = true;
else $hidecnt = false;
//$hidecnt = false;
if ($where) $where = "\nWHERE $where";
if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");
if (!$aggfield) $hidecnt = false;
$sel = "$rowfields, ";
if (is_array($colfield)) {
foreach ($colfield as $k => $v) {
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
if ($aggfield)
$sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
}
} else {
foreach ($colarr as $v) {
if (!is_numeric($v)) $vq = $db->qstr($v);
else $vq = $v;
if (strlen($v) == 0 ) $v = 'null';
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
if ($aggfield) {
if ($hidecnt) $label = $v;
else $label = "{$v}_$aggfield";
$sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
}
}
}
if ($aggfield && $aggfield != '1'){
$agg = "$aggfn($aggfield)";
$sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";
}
if ($showcount)
$sel .= "\n\tSUM(1) as Total";
$sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";
return $sql;
}
/* EXAMPLES USING MS NORTHWIND DATABASE */
if (0) {
# example1
#
# Query the main "product" table
# Set the rows to CompanyName and QuantityPerUnit
# and the columns to the Categories
# and define the joins to link to lookup tables
# "categories" and "suppliers"
#
$sql = PivotTableSQL(
$gDB, # adodb connection
'products p ,categories c ,suppliers s', # tables
'CompanyName,QuantityPerUnit', # row fields
'CategoryName', # column fields
'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
);
print "<pre>$sql";
$rs = $gDB->Execute($sql);
rs2html($rs);
/*
Generated SQL:
SELECT CompanyName,QuantityPerUnit,
SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages",
SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments",
SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections",
SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products",
SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals",
SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry",
SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce",
SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood",
SUM(1) as Total
FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID
GROUP BY CompanyName,QuantityPerUnit
*/
//=====================================================================
# example2
#
# Query the main "product" table
# Set the rows to CompanyName and QuantityPerUnit
# and the columns to the UnitsInStock for different ranges
# and define the joins to link to lookup tables
# "categories" and "suppliers"
#
$sql = PivotTableSQL(
$gDB, # adodb connection
'products p ,categories c ,suppliers s', # tables
'CompanyName,QuantityPerUnit', # row fields
# column ranges
array(
' 0 ' => 'UnitsInStock <= 0',
"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
"11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15',
"16+" =>'15 < UnitsInStock'
),
' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
'UnitsInStock', # sum this field
'Sum' # sum label prefix
);
print "<pre>$sql";
$rs = $gDB->Execute($sql);
rs2html($rs);
/*
Generated SQL:
SELECT CompanyName,QuantityPerUnit,
SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum 0 ",
SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5",
SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10",
SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15",
SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
SUM(UnitsInStock) AS "Sum UnitsInStock",
SUM(1) as Total
FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID
GROUP BY CompanyName,QuantityPerUnit
*/
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Requires PHP4.01pl2 or later because it uses include_once
*/
/*
* Concept from [email protected].
*
* @param db Adodb database connection
* @param tables List of tables to join
* @rowfields List of fields to display on each row
* @colfield Pivot field to slice and display in columns, if we want to calculate
* ranges, we pass in an array (see example2)
* @where Where clause. Optional.
* @aggfield This is the field to sum. Optional.
* Since 2.3.1, if you can use your own aggregate function
* instead of SUM, eg. $sumfield = 'AVG(fieldname)';
* @sumlabel Prefix to display in sum columns. Optional.
* @aggfn Aggregate function to use (could be AVG, SUM, COUNT)
* @showcount Show count of records
*
* @returns Sql generated
*/
function PivotTableSQL($db,$tables,$rowfields,$colfield, $where=false,
$aggfield = false,$sumlabel='Sum ',$aggfn ='SUM', $showcount = true)
{
if ($aggfield) $hidecnt = true;
else $hidecnt = false;
/* $hidecnt = false; */
if ($where) $where = "\nWHERE $where";
if (!is_array($colfield)) $colarr = $db->GetCol("select distinct $colfield from $tables $where order by 1");
if (!$aggfield) $hidecnt = false;
$sel = "$rowfields, ";
if (is_array($colfield)) {
foreach ($colfield as $k => $v) {
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $v THEN 1 ELSE 0 END) AS \"$k\", ";
if ($aggfield)
$sel .= "\n\t$aggfn(CASE WHEN $v THEN $aggfield ELSE 0 END) AS \"$sumlabel$k\", ";
}
} else {
foreach ($colarr as $v) {
if (!is_numeric($v)) $vq = $db->qstr($v);
else $vq = $v;
if (strlen($v) == 0 ) $v = 'null';
if (!$hidecnt) $sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN 1 ELSE 0 END) AS \"$v\", ";
if ($aggfield) {
if ($hidecnt) $label = $v;
else $label = "{$v}_$aggfield";
$sel .= "\n\t$aggfn(CASE WHEN $colfield=$vq THEN $aggfield ELSE 0 END) AS \"$label\", ";
}
}
}
if ($aggfield && $aggfield != '1'){
$agg = "$aggfn($aggfield)";
$sel .= "\n\t$agg as \"$sumlabel$aggfield\", ";
}
if ($showcount)
$sel .= "\n\tSUM(1) as Total";
$sql = "SELECT $sel \nFROM $tables $where \nGROUP BY $rowfields";
return $sql;
}
/* EXAMPLES USING MS NORTHWIND DATABASE */
if (0) {
# example1
#
# Query the main "product" table
# Set the rows to CompanyName and QuantityPerUnit
# and the columns to the Categories
# and define the joins to link to lookup tables
# "categories" and "suppliers"
#
$sql = PivotTableSQL(
$gDB, # adodb connection
'products p ,categories c ,suppliers s', # tables
'CompanyName,QuantityPerUnit', # row fields
'CategoryName', # column fields
'p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID' # joins/where
);
print "<pre>$sql";
$rs = $gDB->Execute($sql);
rs2html($rs);
/*
Generated SQL:
SELECT CompanyName,QuantityPerUnit,
SUM(CASE WHEN CategoryName='Beverages' THEN 1 ELSE 0 END) AS "Beverages",
SUM(CASE WHEN CategoryName='Condiments' THEN 1 ELSE 0 END) AS "Condiments",
SUM(CASE WHEN CategoryName='Confections' THEN 1 ELSE 0 END) AS "Confections",
SUM(CASE WHEN CategoryName='Dairy Products' THEN 1 ELSE 0 END) AS "Dairy Products",
SUM(CASE WHEN CategoryName='Grains/Cereals' THEN 1 ELSE 0 END) AS "Grains/Cereals",
SUM(CASE WHEN CategoryName='Meat/Poultry' THEN 1 ELSE 0 END) AS "Meat/Poultry",
SUM(CASE WHEN CategoryName='Produce' THEN 1 ELSE 0 END) AS "Produce",
SUM(CASE WHEN CategoryName='Seafood' THEN 1 ELSE 0 END) AS "Seafood",
SUM(1) as Total
FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID
GROUP BY CompanyName,QuantityPerUnit
*/
/* ===================================================================== */
# example2
#
# Query the main "product" table
# Set the rows to CompanyName and QuantityPerUnit
# and the columns to the UnitsInStock for different ranges
# and define the joins to link to lookup tables
# "categories" and "suppliers"
#
$sql = PivotTableSQL(
$gDB, # adodb connection
'products p ,categories c ,suppliers s', # tables
'CompanyName,QuantityPerUnit', # row fields
# column ranges
array(
' 0 ' => 'UnitsInStock <= 0',
"1 to 5" => '0 < UnitsInStock and UnitsInStock <= 5',
"6 to 10" => '5 < UnitsInStock and UnitsInStock <= 10',
"11 to 15" => '10 < UnitsInStock and UnitsInStock <= 15',
"16+" =>'15 < UnitsInStock'
),
' p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID', # joins/where
'UnitsInStock', # sum this field
'Sum' # sum label prefix
);
print "<pre>$sql";
$rs = $gDB->Execute($sql);
rs2html($rs);
/*
Generated SQL:
SELECT CompanyName,QuantityPerUnit,
SUM(CASE WHEN UnitsInStock <= 0 THEN UnitsInStock ELSE 0 END) AS "Sum 0 ",
SUM(CASE WHEN 0 < UnitsInStock and UnitsInStock <= 5 THEN UnitsInStock ELSE 0 END) AS "Sum 1 to 5",
SUM(CASE WHEN 5 < UnitsInStock and UnitsInStock <= 10 THEN UnitsInStock ELSE 0 END) AS "Sum 6 to 10",
SUM(CASE WHEN 10 < UnitsInStock and UnitsInStock <= 15 THEN UnitsInStock ELSE 0 END) AS "Sum 11 to 15",
SUM(CASE WHEN 15 < UnitsInStock THEN UnitsInStock ELSE 0 END) AS "Sum 16+",
SUM(UnitsInStock) AS "Sum UnitsInStock",
SUM(1) as Total
FROM products p ,categories c ,suppliers s WHERE p.CategoryID = c.CategoryID and s.SupplierID= p.SupplierID
GROUP BY CompanyName,QuantityPerUnit
*/
}
?>
+48 -2599
View File
File diff suppressed because it is too large Load Diff
+53 -51
View File
@@ -1,52 +1,54 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Requires PHP4.01pl2 or later because it uses include_once
*/
/*
Filter all fields and all rows in a recordset and returns the
processed recordset. We scroll to the beginning of the new recordset
after processing.
We pass a recordset and function name to RSFilter($rs,'rowfunc');
and the function will be called multiple times, once
for each row in the recordset. The function will be passed
an array containing one row repeatedly.
Example:
// ucwords() every element in the recordset
function do_ucwords(&$arr,$rs)
{
foreach($arr as $k => $v) {
$arr[$k] = ucwords($v);
}
}
$rs = RSFilter($rs,'do_ucwords');
*/
function &RSFilter($rs,$fn)
{
if ($rs->databaseType != 'array') {
$rs = &$rs->connection->_rs2rs($rs);
}
$rows = $rs->RecordCount();
for ($i=0; $i < $rows; $i++) {
$fn($rs->_array[$i],$rs);
}
if (!$rs->EOF) {
$rs->_currentRow = 0;
$rs->fields = $rs->_array[0];
}
return $rs;
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Requires PHP4.01pl2 or later because it uses include_once
*/
/*
Filter all fields and all rows in a recordset and returns the
processed recordset. We scroll to the beginning of the new recordset
after processing.
We pass a recordset and function name to RSFilter($rs,'rowfunc');
and the function will be called multiple times, once
for each row in the recordset. The function will be passed
an array containing one row repeatedly.
Example:
// ucwords() every element in the recordset
function do_ucwords(&$arr,$rs)
{
foreach($arr as $k => $v) {
$arr[$k] = ucwords($v);
}
}
$rs = RSFilter($rs,'do_ucwords');
*/
function &RSFilter($rs,$fn)
{
if ($rs->databaseType != 'array') {
if (!$rs->connection) return false;
$rs = &$rs->connection->_rs2rs($rs);
}
$rows = $rs->RecordCount();
for ($i=0; $i < $rows; $i++) {
$fn($rs->_array[$i],$rs);
}
if (!$rs->EOF) {
$rs->_currentRow = 0;
$rs->fields = $rs->_array[0];
}
return $rs;
}
?>
+96 -96
View File
@@ -1,97 +1,97 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*/
/* Documentation on usage is at http://php.weblogs.com/adodb_csv
*
* Legal query string parameters:
*
* sql = holds sql string
* nrows = number of rows to return
* offset = skip offset rows of data
* fetch = $ADODB_FETCH_MODE
*
* example:
*
* http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2
*/
/*
* Define the IP address you want to accept requests from
* as a security measure. If blank we accept anyone promisciously!
*/
$ACCEPTIP = '';
/*
* Connection parameters
*/
$driver = 'mysql';
$host = 'localhost'; // DSN for odbc
$uid = 'root';
$pwd = '';
$database = 'northwind';
/*============================ DO NOT MODIFY BELOW HERE =================================*/
// $sep must match csv2rs() in adodb.inc.php
$sep = ' :::: ';
include('./adodb.inc.php');
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
function err($s)
{
die('**** '.$s.' ');
}
// undo stupid magic quotes
function undomq(&$m)
{
if (get_magic_quotes_gpc()) {
// undo the damage
$m = str_replace('\\\\','\\',$m);
$m = str_replace('\"','"',$m);
$m = str_replace('\\\'','\'',$m);
}
return $m;
}
///////////////////////////////////////// DEFINITIONS
$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"];
if (empty($HTTP_GET_VARS['sql'])) err('No SQL');
if (!empty($ACCEPTIP))
if ($remote != '127.0.0.1' && $remote != $ACCEPTIP)
err("Unauthorised client: '$remote'");
$conn = &ADONewConnection($driver);
if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
$sql = undomq($HTTP_GET_VARS['sql']);
if (isset($HTTP_GET_VARS['fetch']))
$ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];
if (isset($HTTP_GET_VARS['nrows'])) {
$nrows = $HTTP_GET_VARS['nrows'];
$offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;
$rs = $conn->SelectLimit($sql,$nrows,$offset);
} else
$rs = $conn->Execute($sql);
if ($rs){
//$rs->timeToLive = 1;
echo _rs2serialize($rs,$conn,$sql);
$rs->Close();
} else
err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*/
/* Documentation on usage is at http://php.weblogs.com/adodb_csv
*
* Legal query string parameters:
*
* sql = holds sql string
* nrows = number of rows to return
* offset = skip offset rows of data
* fetch = $ADODB_FETCH_MODE
*
* example:
*
* http://localhost/php/server.php?select+*+from+table&nrows=10&offset=2
*/
/*
* Define the IP address you want to accept requests from
* as a security measure. If blank we accept anyone promisciously!
*/
$ACCEPTIP = '';
/*
* Connection parameters
*/
$driver = 'mysql';
$host = 'localhost'; /* DSN for odbc */
$uid = 'root';
$pwd = '';
$database = 'northwind';
/*============================ DO NOT MODIFY BELOW HERE =================================*/
/* $sep must match csv2rs() in adodb.inc.php */
$sep = ' :::: ';
include('./adodb.inc.php');
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
function err($s)
{
die('**** '.$s.' ');
}
/* undo stupid magic quotes */
function undomq(&$m)
{
if (get_magic_quotes_gpc()) {
/* undo the damage */
$m = str_replace('\\\\','\\',$m);
$m = str_replace('\"','"',$m);
$m = str_replace('\\\'','\'',$m);
}
return $m;
}
/* /////////////////////////////////////// DEFINITIONS */
$remote = $HTTP_SERVER_VARS["REMOTE_ADDR"];
if (empty($HTTP_GET_VARS['sql'])) err('No SQL');
if (!empty($ACCEPTIP))
if ($remote != '127.0.0.1' && $remote != $ACCEPTIP)
err("Unauthorised client: '$remote'");
$conn = &ADONewConnection($driver);
if (!$conn->Connect($host,$uid,$pwd,$database)) err($conn->ErrorNo(). $sep . $conn->ErrorMsg());
$sql = undomq($HTTP_GET_VARS['sql']);
if (isset($HTTP_GET_VARS['fetch']))
$ADODB_FETCH_MODE = $HTTP_GET_VARS['fetch'];
if (isset($HTTP_GET_VARS['nrows'])) {
$nrows = $HTTP_GET_VARS['nrows'];
$offset = isset($HTTP_GET_VARS['offset']) ? $HTTP_GET_VARS['offset'] : -1;
$rs = $conn->SelectLimit($sql,$nrows,$offset);
} else
$rs = $conn->Execute($sql);
if ($rs){
/* $rs->timeToLive = 1; */
echo _rs2serialize($rs,$conn,$sql);
$rs->Close();
} else
err($conn->ErrorNo(). $sep .$conn->ErrorMsg());
?>
+85 -85
View File
@@ -1,85 +1,85 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>ADODB Benchmarks</title>
</head>
<body>
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Benchmark code to test the speed to the ADODB library with different databases.
This is a simplistic benchmark to be used as the basis for further testing.
It should not be used as proof of the superiority of one database over the other.
*/
//$testmssql = true;
//$testvfp = true;
$testoracle = true;
//$testado = true;
//$testibase = true;
$testaccess = true;
$testmysql = true;
set_time_limit(240); // increase timeout
include("../tohtml.inc.php");
include("../adodb.inc.php");
function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
{
GLOBAL $ADODB_version,$ADODB_FETCH_MODE;
$max = 100;
$sql = 'select * from ADOXYZ';
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";
// perform query once to cache results so we are only testing throughput
$rs = $db->Execute($sql);
if (!$rs){
print "Error in recordset<p>";
return;
}
$arr = $rs->GetArray();
//$db->debug = true;
$start = microtime();
for ($i=0; $i < $max; $i++) {
$rs = $db->Execute($sql);
$arr = $rs->GetArray();
// print $arr[0][1];
}
$end = microtime();
$start = explode(' ',$start);
$end = explode(' ',$end);
print_r($start);
print_r($end);
// print_r($arr);
$total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);
printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));
flush();
?>
</p>
<table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
</p>
<?php
//$db->Close();
}
include("testdatabases.inc.php");
?>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-/* W3C//DTD HTML 4.0 Transitional//EN"> */
<html>
<head>
<title>ADODB Benchmarks</title>
</head>
<body>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Benchmark code to test the speed to the ADODB library with different databases.
This is a simplistic benchmark to be used as the basis for further testing.
It should not be used as proof of the superiority of one database over the other.
*/
/* $testmssql = true; */
/* $testvfp = true; */
$testoracle = true;
/* $testado = true; */
/* $testibase = true; */
$testaccess = true;
$testmysql = true;
set_time_limit(240); /* increase timeout */
include("../tohtml.inc.php");
include("../adodb.inc.php");
function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
{
GLOBAL $ADODB_version,$ADODB_FETCH_MODE;
$max = 100;
$sql = 'select * from ADOXYZ';
$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
print "<h3>ADODB Version: $ADODB_version Host: <i>$db->host</i> &nbsp; Database: <i>$db->database</i></h3>";
/* perform query once to cache results so we are only testing throughput */
$rs = $db->Execute($sql);
if (!$rs){
print "Error in recordset<p>";
return;
}
$arr = $rs->GetArray();
/* $db->debug = true; */
$start = microtime();
for ($i=0; $i < $max; $i++) {
$rs = $db->Execute($sql);
$arr = $rs->GetArray();
/* print $arr[0][1]; */
}
$end = microtime();
$start = explode(' ',$start);
$end = explode(' ',$end);
print_r($start);
print_r($end);
/* print_r($arr); */
$total = $end[0]+trim($end[1]) - $start[0]-trim($start[1]);
printf ("<p>seconds = %8.2f for %d iterations each with %d records</p>",$total,$max, sizeof($arr));
flush();
?>
</p>
<table width=100% ><tr><td bgcolor=beige>&nbsp;</td></tr></table>
</p>
<?php
/* $db->Close(); */
}
include("testdatabases.inc.php");
?>
</body>
</html>
+194 -194
View File
@@ -1,194 +1,194 @@
<html>
<body bgcolor=white>
<?php
/**
* V3.40 7 April 2003 (c) 2001-2002 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* set tabs to 8
*/
// documentation on usage is at http://php.weblogs.com/adodb_csv
include('../adodb.inc.php');
include('../tohtml.inc.php');
function &send2server($url,$sql)
{
$url .= '?sql='.urlencode($sql);
print "<p>$url</p>";
$rs = csv2rs($url,$err);
if ($err) print $err;
return $rs;
}
function print_pre($s)
{
print "<pre>";print_r($s);print "</pre>";
}
$serverURL = 'http://localhost/php/phplens/adodb/server.php';
$testhttp = false;
$sql1 = "insertz into products (productname) values ('testprod 1')";
$sql2 = "insert into products (productname) values ('testprod 1')";
$sql3 = "insert into products (productname) values ('testprod 2')";
$sql4 = "delete from products where productid>80";
$sql5 = 'select * from products';
if ($testhttp) {
print "<a href=#c>Client Driver Tests</a><p>";
print "<h3>Test Error</h3>";
$rs = send2server($serverURL,$sql1);
print_pre($rs);
print "<hr>";
print "<h3>Test Insert</h3>";
$rs = send2server($serverURL,$sql2);
print_pre($rs);
print "<hr>";
print "<h3>Test Insert2</h3>";
$rs = send2server($serverURL,$sql3);
print_pre($rs);
print "<hr>";
print "<h3>Test Delete</h3>";
$rs = send2server($serverURL,$sql4);
print_pre($rs);
print "<hr>";
print "<h3>Test Select</h3>";
$rs = send2server($serverURL,$sql5);
if ($rs) rs2html($rs);
print "<hr>";
}
print "<a name=c><h1>CLIENT Driver Tests</h1>";
$conn = ADONewConnection('csv');
$conn->Connect($serverURL);
$conn->debug = true;
print "<h3>Bad SQL</h3>";
$rs = $conn->Execute($sql1);
print "<h3>Insert SQL 1</h3>";
$rs = $conn->Execute($sql2);
print "<h3>Insert SQL 2</h3>";
$rs = $conn->Execute($sql3);
print "<h3>Select SQL</h3>";
$rs = $conn->Execute($sql5);
if ($rs) rs2html($rs);
print "<h3>Delete SQL</h3>";
$rs = $conn->Execute($sql4);
print "<h3>Select SQL</h3>";
$rs = $conn->Execute($sql5);
if ($rs) rs2html($rs);
/* EXPECTED RESULTS FOR HTTP TEST:
Test Insert
http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => insert into products (productname) values ('testprod')
[affectedrows] => 1
[insertid] => 81
)
--------------------------------------------------------------------------------
Test Insert2
http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => insert into products (productname) values ('testprod')
[affectedrows] => 1
[insertid] => 82
)
--------------------------------------------------------------------------------
Test Delete
http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => delete from products where productid>80
[affectedrows] => 2
[insertid] => 0
)
[more stuff deleted]
.
.
.
*/
?>
<html>
<body bgcolor=white>
<?php
/**
* V3.60 16 June 2003 (c) 2001-2002 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*
* set tabs to 8
*/
/* documentation on usage is at http://php.weblogs.com/adodb_csv */
include('../adodb.inc.php');
include('../tohtml.inc.php');
function &send2server($url,$sql)
{
$url .= '?sql='.urlencode($sql);
print "<p>$url</p>";
$rs = csv2rs($url,$err);
if ($err) print $err;
return $rs;
}
function print_pre($s)
{
print "<pre>";print_r($s);print "</pre>";
}
$serverURL = 'http:/* localhost/php/phplens/adodb/server.php'; */
$testhttp = false;
$sql1 = "insertz into products (productname) values ('testprod 1')";
$sql2 = "insert into products (productname) values ('testprod 1')";
$sql3 = "insert into products (productname) values ('testprod 2')";
$sql4 = "delete from products where productid>80";
$sql5 = 'select * from products';
if ($testhttp) {
print "<a href=#c>Client Driver Tests</a><p>";
print "<h3>Test Error</h3>";
$rs = send2server($serverURL,$sql1);
print_pre($rs);
print "<hr>";
print "<h3>Test Insert</h3>";
$rs = send2server($serverURL,$sql2);
print_pre($rs);
print "<hr>";
print "<h3>Test Insert2</h3>";
$rs = send2server($serverURL,$sql3);
print_pre($rs);
print "<hr>";
print "<h3>Test Delete</h3>";
$rs = send2server($serverURL,$sql4);
print_pre($rs);
print "<hr>";
print "<h3>Test Select</h3>";
$rs = send2server($serverURL,$sql5);
if ($rs) rs2html($rs);
print "<hr>";
}
print "<a name=c><h1>CLIENT Driver Tests</h1>";
$conn = ADONewConnection('csv');
$conn->Connect($serverURL);
$conn->debug = true;
print "<h3>Bad SQL</h3>";
$rs = $conn->Execute($sql1);
print "<h3>Insert SQL 1</h3>";
$rs = $conn->Execute($sql2);
print "<h3>Insert SQL 2</h3>";
$rs = $conn->Execute($sql3);
print "<h3>Select SQL</h3>";
$rs = $conn->Execute($sql5);
if ($rs) rs2html($rs);
print "<h3>Delete SQL</h3>";
$rs = $conn->Execute($sql4);
print "<h3>Select SQL</h3>";
$rs = $conn->Execute($sql5);
if ($rs) rs2html($rs);
/* EXPECTED RESULTS FOR HTTP TEST:
Test Insert
http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => insert into products (productname) values ('testprod')
[affectedrows] => 1
[insertid] => 81
)
--------------------------------------------------------------------------------
Test Insert2
http://localhost/php/adodb/server.php?sql=insert+into+products+%28productname%29+values+%28%27testprod%27%29
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => insert into products (productname) values ('testprod')
[affectedrows] => 1
[insertid] => 82
)
--------------------------------------------------------------------------------
Test Delete
http://localhost/php/adodb/server.php?sql=delete+from+products+where+productid%3E80
adorecordset Object
(
[dataProvider] => native
[fields] =>
[blobSize] => 64
[canSeek] =>
[EOF] => 1
[emptyTimeStamp] =>
[emptyDate] =>
[debug] =>
[timeToLive] => 0
[bind] =>
[_numOfRows] => -1
[_numOfFields] => 0
[_queryID] => 1
[_currentRow] => -1
[_closed] =>
[_inited] =>
[sql] => delete from products where productid>80
[affectedrows] => 2
[insertid] => 0
)
[more stuff deleted]
.
.
.
*/
?>
+218 -332
View File
@@ -1,333 +1,219 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
USAGE:
// First create a normal connection
$db->NewADOConnection('mysql');
$db->Connect(...);
// Then create a data dictionary object, using this connection
$dict = NewDataDictionary($db);
// We demonstrate creating tables and indexes
$sqlarray = $dict->CreateTableSQL($tabname, $fldarray, $taboptarray);
$dict->ExecuteSQLArray($sqlarray);
$sqlarray = $dict->CreateIndexSQL($idxname, $tabname, $flds);
$dict->ExecuteSQLArray($sqlarray);
FUNCTIONS:
========
function CreateDatabase($dbname, $optionsarray)
========
function CreateTableSQL($tabname, $fldarray, $taboptarray=false)
RETURNS: an array of strings, the sql to be executed, or false
$tabname: name of table
$fldarray: array containing field info
$taboptarray: array containing table options
The format of $fldarray is a 2-dimensional array, where each row in the
1st dimension represents one field. Each row has this format:
array($fieldname, $type, [,$colsize] [,$otheroptions]*)
The first 2 fields must be the field name and the field type. The field type
can be a portable type codes or the actual type for that database.
Legal portable type codes include:
C: varchar
X: CLOB (character large object) or largest varchar size
if CLOB is not supported
C2: Multibyte varchar
X2: Multibyte CLOB
B: BLOB (binary large object)
D: Date (some databases do not support this, and we return a datetime type)
T: Datetime or Timestamp
L: Integer field suitable for storing booleans (0 or 1)
I: Integer (mapped to I4)
I1: 1-byte integer
I2: 2-byte integer
I4: 4-byte integer
I8: 8-byte integer
F: Floating point number
N: Numeric or decimal number
The $colsize field represents the size of the field. If a decimal number is
used, then it is assumed that the number following the dot is the precision,
so 6.2 means a number of size 6 digits and 2 decimal places. It is
recommended that the default for number types be represented as a string to
avoid any rounding errors.
The $otheroptions include the following keywords (case-insensitive):
AUTO For autoincrement number. Emulated with triggers if not available.
Sets NOTNULL also.
AUTOINCREMENT Same as auto.
KEY Primary key field. Sets NOTNULL also. Compound keys are supported.
PRIMARY Same as KEY.
DEFAULT The default value. Character strings are auto-quoted unless
the string begins and ends with spaces, eg ' SYSDATE '.
NOTNULL If field is not null.
DEFDATE Set default value to call function to get today's date.
DEFTIMESTAMP Set default to call function to get today's datetime.
NOQUOTE Prevents autoquoting of default string values.
CONSTRAINTS Additional constraints defined at the end of the field
definition.
Examples:
array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' => 0, 'NotNull')
array('ID', 'I' , 'AUTO')
array('MYDATE', 'D' , 'DEFDATE')
array('NAME', 'C' ,'32',
'CONSTRAINTS' => 'FOREIGN KEY REFERENCES reftable')
The $taboptarray is the 3rd parameter of the CreateTableSQL function.
This contains table specific settings. Legal keywords include
REPLACE Indicates that the previous table definition should be removed
together with ALL data.
CONSTRAINTS Additional constraints defined for the whole table. You will
probably need to prefix this with a comma.
Database specific table options can be defined also using the name of the
database type as the array key. For example:
$taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users');
You can also define foreignkey constraints. The following is syntax for
postgresql:
$taboptarray = array('constraints' =>
', FOREIGN KEY (col1) REFERENCES reftable (refcol)');
========
function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)
RETURNS: an array of strings, the sql to be executed, or false
$idxname: name of index
$tabname: name of table
$fldarray: list of fields as a comma delimited string or an array of strings
$idxoptarray: array of index creation options
$idxoptarray is similar to $taboptarray in that index specific information can
be embedded in the array. Other options include:
CLUSTERED Create clustered index (only mssql)
BITMAP Create bitmap index (only oci8)
UNIQUE Make unique index
FULLTEXT Make fulltext index (only mysql)
HASH Create hash index (only postgres)
========
function AddColumnSQL($tabname, $flds)
========
function AlterColumnSQL($tabname, $flds)
========
function DropColumnSQL($tabname, $flds)
========
function ExecuteSQLArray($sqlarray, $contOnError = true)
RETURNS: 0 if failed, 1 if executed all but with errors, 2 if executed successfully
$sqlarray: an array of strings with sql code (no semicolon at the end of string)
$contOnError: if true, then continue executing even if error occurs
*/
error_reporting(E_ALL);
include_once('../adodb.inc.php');
foreach(array('mysql','oci8','postgres','odbc_mssql') as $dbType) {
echo "<h3>$dbType</h3><p>";
$db = NewADOConnection($dbType);
$dict = NewDataDictionary($db);
if (!$dict) continue;
$dict->debug = 1;
$opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS');
$flds = array(
array('id', 'I',
'AUTO','KEY'),
array('name' => 'firstname', 'type' => 'varchar','size' => 30,
'DEFAULT'=>'Joan'),
array('lastname','varchar',28,
'DEFAULT'=>'Chen','key'),
array('averylonglongfieldname','X',1024,
'NOTNULL','default' => 'test'),
array('price','N','7.2',
'NOTNULL','default' => '0.00'),
array('MYDATE', 'D',
'DEFDATE'),
array('TS','T',
'DEFTIMESTAMP')
);
$sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));
$dict->SetSchema('KUTU');
$sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));
$sqla = array_merge($sqla,$sqli);
$sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));
$sqla = array_merge($sqla,$sqli);
$sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');//,array('BITMAP','FULLTEXT','CLUSTERED'));
$sqla = array_merge($sqla,$sqli);
$addflds = array(array('height', 'F'),array('weight','F'));
$sqli = $dict->AddColumnSQL('testtable',$addflds);
$sqla = array_merge($sqla,$sqli);
$addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));
$sqli = $dict->AlterColumnSQL('testtable',$addflds);
$sqla = array_merge($sqla,$sqli);
print "<pre>";
//print_r($dict->MetaTables());
foreach($sqla as $s) {
$s = htmlspecialchars($s);
print "$s;\n";
if ($dbType == 'oci8') print "/\n";
}
print "</pre><hr>";
}
/***
Generated SQL:
mysql
CREATE DATABASE KUTU;
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id INTEGER NOT NULL AUTO_INCREMENT,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) NOT NULL DEFAULT 'Chen',
averylonglongfieldname LONGTEXT NOT NULL,
price NUMERIC(7,2) NOT NULL DEFAULT 0.00,
MYDATE DATE DEFAULT CURDATE(),
PRIMARY KEY (id, lastname)
)TYPE=ISAM;
CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD height DOUBLE;
ALTER TABLE KUTU.testtable ADD weight DOUBLE;
ALTER TABLE KUTU.testtable MODIFY COLUMN height DOUBLE NOT NULL;
ALTER TABLE KUTU.testtable MODIFY COLUMN weight DOUBLE NOT NULL;
--------------------------------------------------------------------------------
oci8
CREATE USER KUTU IDENTIFIED BY tiger;
/
GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;
/
DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;
/
CREATE TABLE KUTU.testtable (
id NUMBER(16) NOT NULL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname CLOB NOT NULL,
price NUMBER(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATE DEFAULT TRUNC(SYSDATE),
PRIMARY KEY (id, lastname)
)TABLESPACE USERS;
/
DROP SEQUENCE KUTU.SEQ_testtable;
/
CREATE SEQUENCE KUTU.SEQ_testtable;
/
CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable
FOR EACH ROW
BEGIN
select KUTU.SEQ_testtable.nextval into :new.id from dual;
END;
/
CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);
/
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
/
ALTER TABLE testtable ADD (
height NUMBER,
weight NUMBER);
/
ALTER TABLE testtable MODIFY(
height NUMBER NOT NULL,
weight NUMBER NOT NULL);
/
--------------------------------------------------------------------------------
postgres
AlterColumnSQL not supported for PostgreSQL
CREATE DATABASE KUTU LOCATION='/u01/postdata';
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id SERIAL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname TEXT NOT NULL,
price NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATE DEFAULT CURRENT_DATE,
PRIMARY KEY (id, lastname)
);
CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD height FLOAT8;
ALTER TABLE KUTU.testtable ADD weight FLOAT8;
--------------------------------------------------------------------------------
odbc_mssql
CREATE DATABASE KUTU;
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id INT IDENTITY(1,1) NOT NULL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname TEXT NOT NULL,
price NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATETIME DEFAULT GetDate(),
PRIMARY KEY (id, lastname)
);
CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD
height REAL,
weight REAL;
ALTER TABLE KUTU.testtable ALTER COLUMN height REAL NOT NULL;
ALTER TABLE KUTU.testtable ALTER COLUMN weight REAL NOT NULL;
--------------------------------------------------------------------------------
*/
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
*/
error_reporting(E_ALL);
include_once('../adodb.inc.php');
foreach(array('mysql','access','oci8','postgres','odbc_mssql','odbc','sybase','firebird','informix','db2') as $dbType) {
echo "<h3>$dbType</h3><p>";
$db = NewADOConnection($dbType);
$dict = NewDataDictionary($db);
if (!$dict) continue;
$dict->debug = 1;
$opts = array('REPLACE','mysql' => 'TYPE=ISAM', 'oci8' => 'TABLESPACE USERS');
/* $flds = array(
array('id', 'I',
'AUTO','KEY'),
array('name' => 'firstname', 'type' => 'varchar','size' => 30,
'DEFAULT'=>'Joan'),
array('lastname','varchar',28,
'DEFAULT'=>'Chen','key'),
array('averylonglongfieldname','X',1024,
'NOTNULL','default' => 'test'),
array('price','N','7.2',
'NOTNULL','default' => '0.00'),
array('MYDATE', 'D',
'DEFDATE'),
array('TS','T',
'DEFTIMESTAMP')
);*/
$flds = "
ID I AUTO KEY,
FIRSTNAME VARCHAR(30) DEFAULT 'Joan',
LASTNAME VARCHAR(28) DEFAULT 'Chen' key,
averylonglongfieldname X(1024) DEFAULT 'test',
price N(7.2) DEFAULT '0.00',
MYDATE D DEFDATE,
BIGFELLOW X NOTNULL,
TS T DEFTIMESTAMP";
$sqla = $dict->CreateDatabase('KUTU',array('postgres'=>"LOCATION='/u01/postdata'"));
$dict->SetSchema('KUTU');
$sqli = ($dict->CreateTableSQL('testtable',$flds, $opts));
$sqla = array_merge($sqla,$sqli);
$sqli = $dict->CreateIndexSQL('idx','testtable','firstname,lastname',array('BITMAP','FULLTEXT','CLUSTERED','HASH'));
$sqla = array_merge($sqla,$sqli);
$sqli = $dict->CreateIndexSQL('idx2','testtable','price,lastname');/* ,array('BITMAP','FULLTEXT','CLUSTERED')); */
$sqla = array_merge($sqla,$sqli);
$addflds = array(array('height', 'F'),array('weight','F'));
$sqli = $dict->AddColumnSQL('testtable',$addflds);
$sqla = array_merge($sqla,$sqli);
$addflds = array(array('height', 'F','NOTNULL'),array('weight','F','NOTNULL'));
$sqli = $dict->AlterColumnSQL('testtable',$addflds);
$sqla = array_merge($sqla,$sqli);
printsqla($dbType,$sqla);
if ($dbType == 'mysql') {
$db->Connect('localhost', "root", "", "test");
$dict->SetSchema('');
$sqla2 = $dict->ChangeTableSQL('adoxyz',$flds);
if ($sqla2) printsqla($dbType,$sqla2);
}
}
function printsqla($dbType,$sqla)
{
print "<pre>";
/* print_r($dict->MetaTables()); */
foreach($sqla as $s) {
$s = htmlspecialchars($s);
print "$s;\n";
if ($dbType == 'oci8') print "/\n";
}
print "</pre><hr>";
}
/***
Generated SQL:
mysql
CREATE DATABASE KUTU;
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id INTEGER NOT NULL AUTO_INCREMENT,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) NOT NULL DEFAULT 'Chen',
averylonglongfieldname LONGTEXT NOT NULL,
price NUMERIC(7,2) NOT NULL DEFAULT 0.00,
MYDATE DATE DEFAULT CURDATE(),
PRIMARY KEY (id, lastname)
)TYPE=ISAM;
CREATE FULLTEXT INDEX idx ON KUTU.testtable (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD height DOUBLE;
ALTER TABLE KUTU.testtable ADD weight DOUBLE;
ALTER TABLE KUTU.testtable MODIFY COLUMN height DOUBLE NOT NULL;
ALTER TABLE KUTU.testtable MODIFY COLUMN weight DOUBLE NOT NULL;
--------------------------------------------------------------------------------
oci8
CREATE USER KUTU IDENTIFIED BY tiger;
/
GRANT CREATE SESSION, CREATE TABLE,UNLIMITED TABLESPACE,CREATE SEQUENCE TO KUTU;
/
DROP TABLE KUTU.testtable CASCADE CONSTRAINTS;
/
CREATE TABLE KUTU.testtable (
id NUMBER(16) NOT NULL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname CLOB NOT NULL,
price NUMBER(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATE DEFAULT TRUNC(SYSDATE),
PRIMARY KEY (id, lastname)
)TABLESPACE USERS;
/
DROP SEQUENCE KUTU.SEQ_testtable;
/
CREATE SEQUENCE KUTU.SEQ_testtable;
/
CREATE OR REPLACE TRIGGER KUTU.TRIG_SEQ_testtable BEFORE insert ON KUTU.testtable
FOR EACH ROW
BEGIN
select KUTU.SEQ_testtable.nextval into :new.id from dual;
END;
/
CREATE BITMAP INDEX idx ON KUTU.testtable (firstname,lastname);
/
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
/
ALTER TABLE testtable ADD (
height NUMBER,
weight NUMBER);
/
ALTER TABLE testtable MODIFY(
height NUMBER NOT NULL,
weight NUMBER NOT NULL);
/
--------------------------------------------------------------------------------
postgres
AlterColumnSQL not supported for PostgreSQL
CREATE DATABASE KUTU LOCATION='/u01/postdata';
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id SERIAL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname TEXT NOT NULL,
price NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATE DEFAULT CURRENT_DATE,
PRIMARY KEY (id, lastname)
);
CREATE INDEX idx ON KUTU.testtable USING HASH (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD height FLOAT8;
ALTER TABLE KUTU.testtable ADD weight FLOAT8;
--------------------------------------------------------------------------------
odbc_mssql
CREATE DATABASE KUTU;
DROP TABLE KUTU.testtable;
CREATE TABLE KUTU.testtable (
id INT IDENTITY(1,1) NOT NULL,
firstname VARCHAR(30) DEFAULT 'Joan',
lastname VARCHAR(28) DEFAULT 'Chen' NOT NULL,
averylonglongfieldname TEXT NOT NULL,
price NUMERIC(7,2) DEFAULT 0.00 NOT NULL,
MYDATE DATETIME DEFAULT GetDate(),
PRIMARY KEY (id, lastname)
);
CREATE CLUSTERED INDEX idx ON KUTU.testtable (firstname,lastname);
CREATE INDEX idx2 ON KUTU.testtable (price,lastname);
ALTER TABLE KUTU.testtable ADD
height REAL,
weight REAL;
ALTER TABLE KUTU.testtable ALTER COLUMN height REAL NOT NULL;
ALTER TABLE KUTU.testtable ALTER COLUMN weight REAL NOT NULL;
--------------------------------------------------------------------------------
*/
?>
+1227 -1208
View File
File diff suppressed because it is too large Load Diff
+41 -41
View File
@@ -1,41 +1,41 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Untitled</title>
</head>
<body>
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
*/
#
# test connecting to 2 MySQL databases simultaneously and ensure that each connection
# is independant.
#
include("../tohtml.inc.php");
include("../adodb.inc.php");
ADOLoadCode('mysql');
$c1 = ADONewConnection('oci8');
if (!$c1->PConnect('','scott','tiger'))
die("Cannot connect to server");
$c1->debug=1;
$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');
print "Records=".$rs->RecordCount()."<br><pre>";
//$rs->_array = false;
//$rs->connection = false;
//print_r($rs);
rs2html($rs);
?>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-/* W3C//DTD HTML 4.0 Transitional//EN"> */
<html>
<head>
<title>Untitled</title>
</head>
<body>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
*/
#
# test connecting to 2 MySQL databases simultaneously and ensure that each connection
# is independant.
#
include("../tohtml.inc.php");
include("../adodb.inc.php");
ADOLoadCode('mysql');
$c1 = ADONewConnection('oci8');
if (!$c1->PConnect('','scott','tiger'))
die("Cannot connect to server");
$c1->debug=1;
$rs = $c1->Execute('select rownum, p1.firstname,p2.lastname,p2.firstname,p1.lastname from adoxyz p1, adoxyz p2');
print "Records=".$rs->RecordCount()."<br><pre>";
/* $rs->_array = false; */
/* $rs->connection = false; */
/* print_r($rs); */
rs2html($rs);
?>
</body>
</html>
+31 -31
View File
@@ -1,32 +1,32 @@
<code>
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
*/
#
# Code to test Move
#
include("../adodb.inc.php");
$c1 = &ADONewConnection('postgres');
if (!$c1->PConnect("susetikus","tester","test","test"))
die("Cannot connect to database");
# select * from last table in DB
$rs = $c1->Execute("select * from adoxyz order by 1");
$i = 0;
$max = $rs->RecordCount();
if ($max == -1) "RecordCount returns -1<br>";
while (!$rs->EOF and $i < $max) {
$rs->Move($i);
print_r( $rs->fields);
print '<BR>';
$i++;
}
?>
<code>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 8.
*/
#
# Code to test Move
#
include("../adodb.inc.php");
$c1 = &ADONewConnection('postgres');
if (!$c1->PConnect("susetikus","tester","test","test"))
die("Cannot connect to database");
# select * from last table in DB
$rs = $c1->Execute("select * from adoxyz order by 1");
$i = 0;
$max = $rs->RecordCount();
if ($max == -1) "RecordCount returns -1<br>";
while (!$rs->EOF and $i < $max) {
$rs->Move($i);
print_r( $rs->fields);
print '<BR>';
$i++;
}
?>
</code>
+84 -84
View File
@@ -1,85 +1,85 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Test GetUpdateSQL and GetInsertSQL.
*/
error_reporting(E_ALL);
function testsql()
{
include('../adodb.inc.php');
include('../tohtml.inc.php');
//==========================
// This code tests an insert
$sql = "
SELECT *
FROM ADOXYZ WHERE id = -1";
// Select an empty record from the database
$conn = &ADONewConnection("mysql"); // create a connection
//$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
$conn->debug=1;
$conn->PConnect("localhost", "root", "", "test"); // connect to MySQL, testdb
$conn->Execute("delete from adoxyz where lastname like 'Smith%'");
$rs = $conn->Execute($sql); // Execute the query and get the empty recordset
$record = array(); // Initialize an array to hold the record data to insert
// Set the values for the fields in the record
$record["firstname"] = "null";
$record["lastname"] = "Smith\$@//";
$record["created"] = time();
$record["id"] = -1;
// Pass the empty recordset and the array containing the data to insert
// into the GetInsertSQL function. The function will process the data and return
// a fully formatted insert sql statement.
$insertSQL = $conn->GetInsertSQL($rs, $record);
$conn->Execute($insertSQL); // Insert the record into the database
//==========================
// This code tests an update
$sql = "
SELECT *
FROM ADOXYZ WHERE lastname=".$conn->qstr($record['lastname']);
// Select a record to update
$rs = $conn->Execute($sql); // Execute the query and get the existing record to update
if (!$rs) print "<p>No record found!</p>";
$record = array(); // Initialize an array to hold the record data to update
// Set the values for the fields in the record
$record["firstName"] = "Caroline".rand();
$record["lasTname"] = "Smithy"; // Update Caroline's lastname from Miranda to Smith
$record["creAted"] = '2002-12-'.(rand()%30+1);
// Pass the single record recordset and the array containing the data to update
// into the GetUpdateSQL function. The function will process the data and return
// a fully formatted update sql statement.
// If the data has not changed, no recordset is returned
$updateSQL = $conn->GetUpdateSQL($rs, $record);
$conn->Execute($updateSQL); // Update the record in the database
print "<p>Rows Affected=".$conn->Affected_Rows()."</p>";
rs2html($conn->Execute("select * from adoxyz where lastname like 'Smith%'"));
}
testsql();
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Test GetUpdateSQL and GetInsertSQL.
*/
error_reporting(E_ALL);
function testsql()
{
include('../adodb.inc.php');
include('../tohtml.inc.php');
/* ========================== */
/* This code tests an insert */
$sql = "
SELECT *
FROM ADOXYZ WHERE id = -1";
/* Select an empty record from the database */
$conn = &ADONewConnection("mysql"); /* create a connection */
/* $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; */
$conn->debug=1;
$conn->PConnect("localhost", "root", "", "test"); /* connect to MySQL, testdb */
$conn->Execute("delete from adoxyz where lastname like 'Smith%'");
$rs = $conn->Execute($sql); /* Execute the query and get the empty recordset */
$record = array(); /* Initialize an array to hold the record data to insert */
/* Set the values for the fields in the record */
$record["firstname"] = "null";
$record["lastname"] = "Smith\$@/* "; */
$record["created"] = time();
$record["id"] = -1;
/* Pass the empty recordset and the array containing the data to insert */
/* into the GetInsertSQL function. The function will process the data and return */
/* a fully formatted insert sql statement. */
$insertSQL = $conn->GetInsertSQL($rs, $record);
$conn->Execute($insertSQL); /* Insert the record into the database */
/* ========================== */
/* This code tests an update */
$sql = "
SELECT *
FROM ADOXYZ WHERE lastname=".$conn->qstr($record['lastname']);
/* Select a record to update */
$rs = $conn->Execute($sql); /* Execute the query and get the existing record to update */
if (!$rs) print "<p>No record found!</p>";
$record = array(); /* Initialize an array to hold the record data to update */
/* Set the values for the fields in the record */
$record["firstName"] = "Caroline".rand();
$record["lasTname"] = "Smithy"; /* Update Caroline's lastname from Miranda to Smith */
$record["creAted"] = '2002-12-'.(rand()%30+1);
/* Pass the single record recordset and the array containing the data to update */
/* into the GetUpdateSQL function. The function will process the data and return */
/* a fully formatted update sql statement. */
/* If the data has not changed, no recordset is returned */
$updateSQL = $conn->GetUpdateSQL($rs, $record);
$conn->Execute($updateSQL); /* Update the record in the database */
print "<p>Rows Affected=".$conn->Affected_Rows()."</p>";
rs2html($conn->Execute("select * from adoxyz where lastname like 'Smith%'"));
}
testsql();
?>
+47 -47
View File
@@ -1,47 +1,47 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
// Select an empty record from the database
include('../adodb.inc.php');
include('../tohtml.inc.php');
include('../adodb-errorpear.inc.php');
if (0) {
$conn = &ADONewConnection('mysql');
$conn->debug=1;
$conn->PConnect("localhost","root","","xphplens");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection("oci8"); // create a connection
$conn->debug=1;
$conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); // connect to MySQL, testdb
print $conn->databaseType.':'.$conn->GenID();
}
if (0) {
$conn = &ADONewConnection("ibase"); // create a connection
$conn->debug=1;
$conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); // connect to MySQL, testdb
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection('postgres');
$conn->debug=1;
@$conn->PConnect("susetikus","tester","test","test");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
?>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
/* Select an empty record from the database */
include('../adodb.inc.php');
include('../tohtml.inc.php');
include('../adodb-errorpear.inc.php');
if (0) {
$conn = &ADONewConnection('mysql');
$conn->debug=1;
$conn->PConnect("localhost","root","","xphplens");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection("oci8"); /* create a connection */
$conn->debug=1;
$conn->PConnect("falcon", "scott", "tiger", "juris8.ecosystem.natsoft.com.my"); /* connect to MySQL, testdb */
print $conn->databaseType.':'.$conn->GenID();
}
if (0) {
$conn = &ADONewConnection("ibase"); /* create a connection */
$conn->debug=1;
$conn->Connect("localhost:c:\\Interbase\\Examples\\Database\\employee.gdb", "sysdba", "masterkey", ""); /* connect to MySQL, testdb */
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
if (0) {
$conn = &ADONewConnection('postgres');
$conn->debug=1;
@$conn->PConnect("susetikus","tester","test","test");
print $conn->databaseType.':'.$conn->GenID().'<br>';
}
?>
+28 -28
View File
@@ -1,29 +1,29 @@
<html>
<body>
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));
include("../adodb.inc.php");
if (isset($access)) {
$db=ADONewConnection('access');
$db->PConnect('nwind');
} else {
$db = ADONewConnection('mysql');
$db->PConnect('mangrove','root','','xphplens');
}
if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');
else $rs = $db->Execute('select * from products');
$arr = $rs->GetArray();
print sizeof($arr);
<html>
<body>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
$ADODB_CACHE_DIR = dirname(tempnam('/tmp',''));
include("../adodb.inc.php");
if (isset($access)) {
$db=ADONewConnection('access');
$db->PConnect('nwind');
} else {
$db = ADONewConnection('mysql');
$db->PConnect('mangrove','root','','xphplens');
}
if (isset($cache)) $rs = $db->CacheExecute(120,'select * from products');
else $rs = $db->Execute('select * from products');
$arr = $rs->GetArray();
print sizeof($arr);
?>
+235 -208
View File
@@ -1,208 +1,235 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*/
/* this file is used by the ADODB test program: test.php */
// cannot test databases below, but we include them anyway to check
// if they parse ok...
ADOLoadCode("sybase");
ADOLoadCode("postgres");
ADOLoadCode("postgres7");
ADOLoadCode("firebird");
ADOLoadCode("borland_ibase");
ADOLoadCode("informix");
ADOLoadCode("sqlanywhere");
flush();
if (!empty($testpostgres)) {
//ADOLoadCode("postgres");
$db = &ADONewConnection('postgres');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("localhost","tester","test","test")) {
testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");
}else
print "ERROR: PostgreSQL requires a database called test on server susetikus, user tester, password test.<BR>".$db->ErrorMsg();
}
if (!empty($testibase)) {
$db = &ADONewConnection('firebird');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", ""))
testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");
else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();
}
// REQUIRES ODBC DSN CALLED nwind
if (!empty($testaccess)) {
$db = &ADONewConnection('access');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("nwind", "", "", ""))
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";
}
if (!empty($testaccess) && !empty($testado)) { // ADO ACCESS
$db = &ADONewConnection("ado_access");
print "<h1>Connecting $db->databaseType...</h1>";
$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
$myDSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
. 'DATA SOURCE=' . $access . ';';
//. 'USER ID=;PASSWORD=;';
if (@$db->PConnect($myDSN, "", "", "")) {
print "ADO version=".$db->_connectionID->version."<br>";
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
} else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();
}
if (!empty($testvfp)) { // ODBC
$db = &ADONewConnection('vfp');
print "<h1>Connecting $db->databaseType...</h1>";flush();
if ( $db->PConnect("vfp-adoxyz")) {
testdb($db,"create table d:\\inetpub\\wwwroot\\php\\vfp\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
} else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=logos2, VFP driver";
}
// REQUIRES MySQL server at localhost with database 'test'
if (!empty($testmysql)) { // MYSQL
$db = &ADONewConnection('mysql');
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
else $server = "mangrove";
if ($db->PConnect('jaguar', "mobydick", "", "test"))
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
// REQUIRES MySQL server at localhost with database 'test'
if (!empty($testmysqlodbc)) { // MYSQL
$db = &ADONewConnection('odbc');
$db->hasTransactions = false;
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
else $server = "mangrove";
if ($db->PConnect('mysql', "mobydick", ""))
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
if (!empty($testproxy)){
$db = &ADONewConnection('proxy');
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
if ($db->PConnect('http://localhost/php/phplens/adodb/server.php'))
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode('oci805');
ADOLoadCode("oci8po");
if (!empty($testoracle)) {
$db = ADONewConnection('oci8po');
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->NConnect('', "scott", "tiger",'natsoft.ecosystem.natsoft.com.my'))
//if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my"))
testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode("oracle"); // no longer supported
if (false && !empty($testoracle)) {
$db = ADONewConnection();
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))
testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode("odbc_mssql");
if (!empty($testmssql)) { // MS SQL Server via ODBC
$db = ADONewConnection();
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("netsdk", "adodb", "natsoft", "")) {
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
}
else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
}
ADOLoadCode("ado_mssql");
if (!empty($testmssql) && !empty($testado) ) { // ADO ACCESS MSSQL -- thru ODBC -- DSN-less
$db = &ADONewConnection("ado_mssql");
$db->debug=1;
print "<h1>Connecting DSN-less $db->databaseType...</h1>";
$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
. "SERVER=JAGUAR\VSDOTNET;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No" ;
if (@$db->PConnect($myDSN, "", "", ""))
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
else print "ERROR: MSSQL test 2 requires MS SQL 7";
}
ADOLoadCode("mssqlpo");
if (!empty($testmssql)) { // MS SQL Server -- the extension is buggy -- probably better to use ODBC
$db = ADONewConnection();
$db->debug=1;
print "<h1>Connecting $db->databaseType...</h1>";
$db->PConnect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
if (true or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {
AutoDetect_MSSQL_Date_Order($db);
// $db->Execute('drop table adoxyz');
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
} else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();
}
if (!empty($testmssql) && !empty($testado)) { // ADO ACCESS MSSQL with OLEDB provider
$db = &ADONewConnection("ado_mssql");
print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";
$db->debug=1;
$myDSN="SERVER=(local)\NetSDK;DATABASE=northwind;Trusted_Connection=yes";
//$myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;';
if ($db->PConnect($myDSN, "sa", "natsoft", 'SQLOLEDB'))
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";
}
print "<h3>Tests Completed</h3>";
?>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
*/
/* this file is used by the ADODB test program: test.php */
/* cannot test databases below, but we include them anyway to check */
/* if they parse ok... */
ADOLoadCode("sybase");
ADOLoadCode("postgres");
ADOLoadCode("postgres7");
ADOLoadCode("firebird");
ADOLoadCode("borland_ibase");
ADOLoadCode("informix");
ADOLoadCode("sqlanywhere");
flush();
if (!empty($testpostgres)) {
/* ADOLoadCode("postgres"); */
$db = &ADONewConnection('postgres');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("localhost","tester","test","test")) {
testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname varchar,created date)");
}else
print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
}
if (!empty($testpgodbc)) {
$db = &ADONewConnection('odbc');
$db->hasTransactions = false;
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->PConnect('Postgresql')) {
$db->hasTransactions = true;
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
} else print "ERROR: PostgreSQL requires a database called test on server, user tester, password test.<BR>".$db->ErrorMsg();
}
if (!empty($testibase)) {
$db = &ADONewConnection('firebird');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", ""))
testdb($db,"create table ADOXYZ (id integer, firstname char(24), lastname char(24),price numeric(12,2),created date)");
else print "ERROR: Interbase test requires a database called employee.gdb".'<BR>'.$db->ErrorMsg();
}
/* REQUIRES ODBC DSN CALLED nwind */
if (!empty($testaccess)) {
$db = &ADONewConnection('access');
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("nwind", "", "", ""))
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
else print "ERROR: Access test requires a Windows ODBC DSN=nwind, Access driver";
}
if (!empty($testaccess) && !empty($testado)) { /* ADO ACCESS */
$db = &ADONewConnection("ado_access");
print "<h1>Connecting $db->databaseType...</h1>";
$access = 'd:\inetpub\wwwroot\php\NWIND.MDB';
$myDSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
. 'DATA SOURCE=' . $access . ';';
/* . 'USER ID=;PASSWORD=;'; */
if (@$db->PConnect($myDSN, "", "", "")) {
print "ADO version=".$db->_connectionID->version."<br>";
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
} else print "ERROR: Access test requires a Access database $access".'<BR>'.$db->ErrorMsg();
}
if (!empty($testvfp)) { /* ODBC */
$db = &ADONewConnection('vfp');
print "<h1>Connecting $db->databaseType...</h1>";flush();
if ( $db->PConnect("vfp-adoxyz")) {
testdb($db,"create table d:\\inetpub\\adodb\\ADOXYZ (id int, firstname char(24), lastname char(24),created date)");
} else print "ERROR: Visual FoxPro test requires a Windows ODBC DSN=vfp-adoxyz, VFP driver";
}
/* REQUIRES MySQL server at localhost with database 'test' */
if (!empty($testmysql)) { /* MYSQL */
$db = &ADONewConnection('mysql');
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
else $server = "mangrove";
if ($db->PConnect($server, "root", "", "test")) {
/* $db->debug=1;$db->Execute('drop table ADOXYZ'); */
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)");
} else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
/* REQUIRES MySQL server at localhost with database 'test' */
if (!empty($testmysqlodbc)) { /* MYSQL */
$db = &ADONewConnection('odbc');
$db->hasTransactions = false;
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
else $server = "mangrove";
if ($db->PConnect('mysql', "root", ""))
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
if (!empty($testproxy)){
$db = &ADONewConnection('proxy');
print "<h1>Connecting $db->databaseType...</h1>";
if ($HTTP_SERVER_VARS['HTTP_HOST'] == 'localhost') $server = 'localhost';
if ($db->PConnect('http:/* localhost/php/phplens/adodb/server.php')) */
testdb($db,
"create table ADOXYZ (id int, firstname char(24), lastname char(24), created date) type=innodb");
else print "ERROR: MySQL test requires a MySQL server on localhost, userid='admin', password='', database='test'".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode('oci805');
ADOLoadCode("oci8po");
if (!empty($testoracle)) {
$db = ADONewConnection('oci8po');
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->Connect('', "scott", "tiger",''))
/* if ($db->PConnect("", "scott", "tiger", "juris.ecosystem.natsoft.com.my")) */
testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode("oracle"); /* no longer supported */
if (false && !empty($testoracle)) {
$db = ADONewConnection();
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->PConnect("", "scott", "tiger", "natsoft.domain"))
testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
else print "ERROR: Oracle test requires an Oracle server setup with scott/tiger".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode("db2"); /* no longer supported */
if (!empty($testdb2)) {
$db = ADONewConnection();
print "<h1>Connecting $db->databaseType...</h1>";
if ($db->Connect("db2_sample", "", "", ""))
testdb($db,"create table ADOXYZ (id int, firstname varchar(24), lastname varchar(24),created date)");
else print "ERROR: DB2 test requires an server setup with odbc data source db2_sample".'<BR>'.$db->ErrorMsg();
}
ADOLoadCode("odbc_mssql");
if (!empty($testmssql)) { /* MS SQL Server via ODBC */
$db = ADONewConnection();
print "<h1>Connecting $db->databaseType...</h1>";
if (@$db->PConnect("mssql-northwind", "adodb", "natsoft", "")) {
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
}
else print "ERROR: MSSQL test 1 requires a MS SQL 7 server setup with DSN setup";
}
ADOLoadCode("ado_mssql");
if (!empty($testmssql) && !empty($testado) ) { /* ADO ACCESS MSSQL -- thru ODBC -- DSN-less */
$db = &ADONewConnection("ado_mssql");
$db->debug=1;
print "<h1>Connecting DSN-less $db->databaseType...</h1>";
$myDSN="PROVIDER=MSDASQL;DRIVER={SQL Server};"
. "SERVER=tigress;DATABASE=NorthWind;UID=adodb;PWD=natsoft;Trusted_Connection=No" ;
if (@$db->PConnect($myDSN, "", "", ""))
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
else print "ERROR: MSSQL test 2 requires MS SQL 7";
}
ADOLoadCode("mssqlpo");
if (!empty($testmssql)) { /* MS SQL Server -- the extension is buggy -- probably better to use ODBC */
$db = ADONewConnection();
$db->debug=1;
print "<h1>Connecting $db->databaseType...</h1>";
$db->PConnect('tigress','adodb','natsoft','northwind');
if (true or @$db->PConnect("mangrove", "sa", "natsoft", "ai")) {
AutoDetect_MSSQL_Date_Order($db);
/* $db->Execute('drop table adoxyz'); */
testdb($db,"create table ADOXYZ (id int, firstname char(24) null, lastname char(24) null,created datetime null)");
} else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='192.168.0.1', userid='sa', password='natsoft', database='ai'".'<BR>'.$db->ErrorMsg();
}
if (!empty($testmssql) && !empty($testado)) { /* ADO ACCESS MSSQL with OLEDB provider */
$db = &ADONewConnection("ado_mssql");
print "<h1>Connecting DSN-less OLEDB Provider $db->databaseType...</h1>";
$db->debug=1;
$myDSN="SERVER=(local)\NetSDK;DATABASE=northwind;Trusted_Connection=yes";
/* $myDSN='SERVER=(local)\NetSDK;DATABASE=northwind;'; */
if ($db->PConnect($myDSN, "sa", "natsoft", 'SQLOLEDB'))
testdb($db,"create table ADOXYZ (id int, firstname char(24), lastname char(24),created datetime)");
else print "ERROR: MSSQL test 2 requires a MS SQL 7 on a server='mangrove', userid='sa', password='', database='ai'";
}
print "<h3>Tests Completed</h3>";
?>
+35 -35
View File
@@ -1,36 +1,36 @@
<?php
/*
V3.40 7 April 2003
Run multiple copies of this php script at the same time
to test unique generation of id's in multiuser mode
*/
include_once('../adodb.inc.php');
$testaccess = true;
include_once('testdatabases.inc.php');
function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
{
$table = 'adodbseq';
$db->Execute("drop table $table");
//$db->debug=true;
$ctr = 5000;
$lastnum = 0;
while (--$ctr >= 0) {
$num = $db->GenID($table);
if ($num === false) {
print "GenID returned false";
break;
}
if ($lastnum + 1 == $num) print " $num ";
else {
print " <font color=red>$num</font> ";
flush();
}
$lastnum = $num;
}
}
<?php
/*
V3.60 16 June 2003
Run multiple copies of this php script at the same time
to test unique generation of id's in multiuser mode
*/
include_once('../adodb.inc.php');
$testaccess = true;
include_once('testdatabases.inc.php');
function testdb(&$db,$createtab="create table ADOXYZ (id int, firstname char(24), lastname char(24), created date)")
{
$table = 'adodbseq';
$db->Execute("drop table $table");
/* $db->debug=true; */
$ctr = 5000;
$lastnum = 0;
while (--$ctr >= 0) {
$num = $db->GenID($table);
if ($num === false) {
print "GenID returned false";
break;
}
if ($lastnum + 1 == $num) print " $num ";
else {
print " <font color=red>$num</font> ";
flush();
}
$lastnum = $num;
}
}
?>
+49 -49
View File
@@ -1,50 +1,50 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Test GetUpdateSQL and GetInsertSQL.
*/
error_reporting(E_ALL);
include('../adodb.inc.php');
include('../tohtml.inc.php');
//==========================
// This code tests an insert
$conn = &ADONewConnection("odbc_mssql"); // create a connection
$conn->Connect('sqlserver','sa','natsoft');
//$conn = &ADONewConnection("mssql");
//$conn->Connect('mangrove','sa','natsoft','ai');
//$conn->Connect('mangrove','sa','natsoft','ai');
$conn->debug=1;
$conn->Execute('delete from blobtest');
$conn->Execute('insert into blobtest (id) values(1)');
$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');
$rs = $conn->Execute('select b1 from blobtest where id=1');
$output = "c:\\temp\\test_out-".date('H-i-s').".gif";
print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";
$fd = fopen($output, "wb");
fwrite($fd, $rs->fields[0]);
fclose($fd);
print " <a href=file://$output>View Image</a>";
//$rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest');
//rs2html($rs);
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Set tabs to 4 for best viewing.
*
* Latest version is available at http://php.weblogs.com
*
* Test GetUpdateSQL and GetInsertSQL.
*/
error_reporting(E_ALL);
include('../adodb.inc.php');
include('../tohtml.inc.php');
/* ========================== */
/* This code tests an insert */
$conn = &ADONewConnection("odbc_mssql"); /* create a connection */
$conn->Connect('mssql-northwind','sa','natsoft');
/* $conn = &ADONewConnection("mssql"); */
/* $conn->Connect('mangrove','sa','natsoft','ai'); */
/* $conn->Connect('mangrove','sa','natsoft','ai'); */
$conn->debug=1;
$conn->Execute('delete from blobtest');
$conn->Execute('insert into blobtest (id) values(1)');
$conn->UpdateBlobFile('blobtest','b1','../cute_icons_for_site/adodb.gif','id=1');
$rs = $conn->Execute('select b1 from blobtest where id=1');
$output = "c:\\temp\\test_out-".date('H-i-s').".gif";
print "Saving file <b>$output</b>, size=".strlen($rs->fields[0])."<p>";
$fd = fopen($output, "wb");
fwrite($fd, $rs->fields[0]);
fclose($fd);
print " <a href=file:/* $output>View Image</a>"; */
/* $rs = $conn->Execute('SELECT id,SUBSTRING(b1, 1, 10) FROM blobtest'); */
/* rs2html($rs); */
?>
+69 -69
View File
@@ -1,70 +1,70 @@
<html>
<body>
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(63);
include("../adodb.inc.php");
include("../tohtml.inc.php");
if (1) {
$db = ADONewConnection('oci8po');
$db->PConnect('','scott','tiger','natsoftmts');
$db->debug = true;
if (!empty($testblob)) {
$varHoldingBlob = 'ABC DEF GEF John TEST';
$num = time()%10240;
// create table atable (id integer, ablob blob);
$db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');
$db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');
$rs = &$db->Execute('select * from atable');
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
$stmt = $db->Prepare('select * from adoxyz where id=?');
for ($i = 1; $i <= 10; $i++) {
$rs = &$db->Execute(
$stmt,
array($i));
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
}
if (1) {
$db = ADONewConnection('oci8');
$db->PConnect('','scott','tiger');
$db->debug = true;
$db->Execute("delete from emp where ename='John'");
print $db->Affected_Rows().'<BR>';
$stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
$rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));
// prepare not quite ready for prime time
//$rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John'));
if (!$rs) die("Empty RS");
}
if (0) {
$db = ADONewConnection('odbc_oracle');
if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');
$db->debug = true;
$rs = &$db->Execute(
'select * from adoxyz where firstname=? and trim(lastname)=?',
array('first'=>'Caroline','last'=>'Miranda'));
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
<html>
<body>
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(63);
include("../adodb.inc.php");
include("../tohtml.inc.php");
if (1) {
$db = ADONewConnection('oci8po');
$db->PConnect('','scott','tiger','natsoftmts');
$db->debug = true;
if (!empty($testblob)) {
$varHoldingBlob = 'ABC DEF GEF John TEST';
$num = time()%10240;
/* create table atable (id integer, ablob blob); */
$db->Execute('insert into ATABLE (id,ablob) values('.$num.',empty_blob())');
$db->UpdateBlob('ATABLE', 'ablob', $varHoldingBlob, 'id='.$num, 'BLOB');
$rs = &$db->Execute('select * from atable');
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
$stmt = $db->Prepare('select * from adoxyz where id=?');
for ($i = 1; $i <= 10; $i++) {
$rs = &$db->Execute(
$stmt,
array($i));
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
}
if (1) {
$db = ADONewConnection('oci8');
$db->PConnect('','scott','tiger');
$db->debug = true;
$db->Execute("delete from emp where ename='John'");
print $db->Affected_Rows().'<BR>';
$stmt = &$db->Prepare('insert into emp (empno, ename) values (:empno, :ename)');
$rs = $db->Execute($stmt,array('empno'=>4321,'ename'=>'John'));
/* prepare not quite ready for prime time */
/* $rs = $db->Execute($stmt,array('empno'=>3775,'ename'=>'John')); */
if (!$rs) die("Empty RS");
}
if (0) {
$db = ADONewConnection('odbc_oracle');
if (!$db->PConnect('local_oracle','scott','tiger')) die('fail connect');
$db->debug = true;
$rs = &$db->Execute(
'select * from adoxyz where firstname=? and trim(lastname)=?',
array('first'=>'Caroline','last'=>'Miranda'));
if (!$rs) die("Empty RS");
if ($rs->EOF) die("EOF RS");
rs2html($rs);
}
?>
+81 -81
View File
@@ -1,82 +1,82 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
/*
Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.
We have 2 examples. The first shows us using the Parameter statement.
The second shows us using the new ExecuteCursor($sql, $cursorName)
function.
------------------------------------------------------------------
-- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus
------------------------------------------------------------------
CREATE or replace PACKAGE adodb AS
TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
-- list all tables that match tablenames in current schema
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
END adodb;
/
CREATE or replace PACKAGE BODY adodb AS
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
BEGIN
OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
END open_tab;
END adodb;
/
------------------------------------------------------------------
-- END PACKAGE
------------------------------------------------------------------
*/
include('../adodb.inc.php');
include('../tohtml.inc.php');
error_reporting(E_ALL);
$db = ADONewConnection('oci8');
$db->PConnect('','scott','tiger');
$db->debug = true;
#---------------------------------------------------------------
# EXAMPLE 1
# explicitly use Parameter function
#---------------------------------------------------------------
$stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'%'); END;");
$db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR);
$rs = $db->Execute($stmt);
if ($rs && !$rs->EOF) {
print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
} else {
print "<b>Error in using Cursor Variables 1</b><p>";
}
#---------------------------------------------------------------
# EXAMPLE 2
# Equivalent of above example 1 using ExecuteCursor($sql,$rsname)
#---------------------------------------------------------------
$rs = $db->ExecuteCursor(
"BEGIN adodb.open_tab(:RS,'%'); END;", # pl/sql script
'RS'); # cursor name
if ($rs && !$rs->EOF) {
print "Test 2 RowCount: ".$rs->RecordCount()."<p>";
rs2html($rs);
} else {
print "<b>Error in using Cursor Variables 2</b><p>";
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
/*
Test for Oracle Variable Cursors, which are treated as ADOdb recordsets.
We have 2 examples. The first shows us using the Parameter statement.
The second shows us using the new ExecuteCursor($sql, $cursorName)
function.
------------------------------------------------------------------
-- TEST PACKAGE YOU NEED TO INSTALL ON ORACLE - run from sql*plus
------------------------------------------------------------------
CREATE or replace PACKAGE adodb AS
TYPE TabType IS REF CURSOR RETURN tab%ROWTYPE;
-- list all tables that match tablenames in current schema
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar);
END adodb;
/
CREATE or replace PACKAGE BODY adodb AS
PROCEDURE open_tab (tabcursor IN OUT TabType,tablenames in varchar) IS
BEGIN
OPEN tabcursor FOR SELECT * FROM tab where tname like tablenames;
END open_tab;
END adodb;
/
------------------------------------------------------------------
-- END PACKAGE
------------------------------------------------------------------
*/
include('../adodb.inc.php');
include('../tohtml.inc.php');
error_reporting(E_ALL);
$db = ADONewConnection('oci8');
$db->PConnect('','scott','tiger');
$db->debug = true;
#---------------------------------------------------------------
# EXAMPLE 1
# explicitly use Parameter function
#---------------------------------------------------------------
$stmt = $db->Prepare("BEGIN adodb.open_tab(:RS,'%'); END;");
$db->Parameter($stmt, $cur, 'RS', false, -1, OCI_B_CURSOR);
$rs = $db->Execute($stmt);
if ($rs && !$rs->EOF) {
print "Test 1 RowCount: ".$rs->RecordCount()."<p>";
} else {
print "<b>Error in using Cursor Variables 1</b><p>";
}
#---------------------------------------------------------------
# EXAMPLE 2
# Equivalent of above example 1 using ExecuteCursor($sql,$rsname)
#---------------------------------------------------------------
$rs = $db->ExecuteCursor(
"BEGIN adodb.open_tab(:RS,'%'); END;", # pl/sql script
'RS'); # cursor name
if ($rs && !$rs->EOF) {
print "Test 2 RowCount: ".$rs->RecordCount()."<p>";
rs2html($rs);
} else {
print "<b>Error in using Cursor Variables 2</b><p>";
}
?>
+82 -82
View File
@@ -1,83 +1,83 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(E_ALL);
include_once('../adodb.inc.php');
include_once('../adodb-pager.inc.php');
$driver = 'oci8';
$sql = 'select ID, firstname as "First Name", lastname as "Last Name" from adoxyz order by id';
//$sql = 'select count(*),firstname from adoxyz group by firstname order by 2 ';
$sql = 'select distinct firstname, lastname from adoxyz order by firstname';
if ($driver == 'postgres') {
$db = NewADOConnection('postgres');
$db->PConnect('localhost','tester','test','test');
}
if ($driver == 'access') {
$db = NewADOConnection('access');
$db->PConnect("nwind", "", "", "");
}
if ($driver == 'ibase') {
$db = NewADOConnection('ibase');
$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");
$sql = 'select distinct firstname, lastname from adoxyz order by firstname';
}
if ($driver == 'mssql') {
$db = NewADOConnection('mssql');
$db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
}
if ($driver == 'oci8') {
$db = NewADOConnection('oci8');
$db->Connect('','scott','tiger');
}
if ($driver == 'access') {
$db = NewADOConnection('access');
$db->Connect('nwind');
}
if (empty($driver) or $driver == 'mysql') {
$db = NewADOConnection('mysql');
$db->Connect('localhost','root','','xphplens');
}
//$db->pageExecuteCountRows = false;
$db->debug = true;
if (0) {
$rs = &$db->Execute($sql);
include_once('../toexport.inc.php');
print "<pre>";
print rs2csv($rs); # return a string
print '<hr>';
$rs->MoveFirst(); # note, some databases do not support MoveFirst
print rs2tab($rs); # return a string
print '<hr>';
$rs->MoveFirst();
rs2tabout($rs); # send to stdout directly
print "</pre>";
}
$pager = new ADODB_Pager($db,$sql);
$pager->showPageLinks = true;
$pager->linksPerPage = 3;
$pager->cache = 60;
$pager->Render($rows=7);
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(E_ALL);
include_once('../adodb.inc.php');
include_once('../adodb-pager.inc.php');
$driver = 'oci8';
$sql = 'select ID, firstname as "First Name", lastname as "Last Name" from adoxyz order by id';
/* $sql = 'select count(*),firstname from adoxyz group by firstname order by 2 '; */
$sql = 'select distinct firstname, lastname from adoxyz order by firstname';
if ($driver == 'postgres') {
$db = NewADOConnection('postgres');
$db->PConnect('localhost','tester','test','test');
}
if ($driver == 'access') {
$db = NewADOConnection('access');
$db->PConnect("nwind", "", "", "");
}
if ($driver == 'ibase') {
$db = NewADOConnection('ibase');
$db->PConnect("localhost:e:\\firebird\\examples\\employee.gdb", "sysdba", "masterkey", "");
$sql = 'select distinct firstname, lastname from adoxyz order by firstname';
}
if ($driver == 'mssql') {
$db = NewADOConnection('mssql');
$db->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
}
if ($driver == 'oci8') {
$db = NewADOConnection('oci8');
$db->Connect('','scott','tiger');
}
if ($driver == 'access') {
$db = NewADOConnection('access');
$db->Connect('nwind');
}
if (empty($driver) or $driver == 'mysql') {
$db = NewADOConnection('mysql');
$db->Connect('localhost','root','','xphplens');
}
/* $db->pageExecuteCountRows = false; */
$db->debug = true;
if (0) {
$rs = &$db->Execute($sql);
include_once('../toexport.inc.php');
print "<pre>";
print rs2csv($rs); # return a string
print '<hr>';
$rs->MoveFirst(); # note, some databases do not support MoveFirst
print rs2tab($rs); # return a string
print '<hr>';
$rs->MoveFirst();
rs2tabout($rs); # send to stdout directly
print "</pre>";
}
$pager = new ADODB_Pager($db,$sql);
$pager->showPageLinks = true;
$pager->linksPerPage = 3;
$pager->cache = 60;
$pager->Render($rows=7);
?>
+33 -33
View File
@@ -1,34 +1,34 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(E_ALL);
include_once('../adodb-pear.inc.php');
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'xphplens';
$driver = 'mysql';
$dsn = "$driver://$username:$password@$hostname/$databasename";
$db = DB::Connect($dsn);
$db->setFetchMode(ADODB_FETCH_ASSOC);
$rs = $db->Query('select firstname,lastname from adoxyz');
$cnt = 0;
while ($arr = $rs->FetchRow()) {
print_r($arr);
print "<br>";
$cnt += 1;
}
if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
error_reporting(E_ALL);
include_once('../adodb-pear.inc.php');
$username = 'root';
$password = '';
$hostname = 'localhost';
$databasename = 'xphplens';
$driver = 'mysql';
$dsn = "$driver:/* $username:$password@$hostname/$databasename"; */
$db = DB::Connect($dsn);
$db->setFetchMode(ADODB_FETCH_ASSOC);
$rs = $db->Query('select firstname,lastname from adoxyz');
$cnt = 0;
while ($arr = $rs->FetchRow()) {
print_r($arr);
print "<br>";
$cnt += 1;
}
if ($cnt != 50) print "<b>Error in \$cnt = $cnt</b>";
?>
+39 -39
View File
@@ -1,40 +1,40 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
function NotifyExpire($ref,$key)
{
print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";
}
$USER = 'JLIM'.rand();
$ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');
GLOBAL $HTTP_SESSION_VARS;
ob_start();
error_reporting(E_ALL);
$ADODB_SESS_DEBUG = true;
include('../adodb-cryptsession.php');
session_start();
print "<h3>PHP ".PHP_VERSION."</h3>";
$HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);
if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";
if (rand() % 10 == 0) {
print "<p>Random session destroy</p>";
session_destroy();
}
print "<hr>";
print_r($HTTP_COOKIE_VARS);
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Set tabs to 4 for best viewing.
Latest version is available at http://php.weblogs.com/
*/
function NotifyExpire($ref,$key)
{
print "<p><b>Notify Expiring=$ref, sessionkey=$key</b></p>";
}
$USER = 'JLIM'.rand();
$ADODB_SESSION_EXPIRE_NOTIFY = array('USER','NotifyExpire');
GLOBAL $HTTP_SESSION_VARS;
ob_start();
error_reporting(E_ALL);
$ADODB_SESS_DEBUG = true;
include('../adodb-cryptsession.php');
session_start();
print "<h3>PHP ".PHP_VERSION."</h3>";
$HTTP_SESSION_VARS['MONKEY'] = array('1','abc',44.41);
if (!isset($HTTP_GET_VARS['nochange'])) @$HTTP_SESSION_VARS['AVAR'] += 1;
print "<p><b>\$HTTP_SESSION_VARS['AVAR']={$HTTP_SESSION_VARS['AVAR']}</b></p>";
if (rand() % 10 == 0) {
print "<p>Random session destroy</p>";
session_destroy();
}
print "<hr>";
print_r($HTTP_COOKIE_VARS);
?>
+4 -4
View File
@@ -1,5 +1,5 @@
<?php
include_once('../adodb-time.inc.php');
adodb_date_test();
<?php
include_once('../adodb-time.inc.php');
adodb_date_test();
?>
+2 -2
View File
@@ -30,7 +30,7 @@ include_once('DB.php');
$hostname = 'JAGUAR\vsdotnet';
$databasename = 'northwind';
$dsn = "mssql://$username:$password@$hostname/$databasename";
$dsn = "mssql:/* $username:$password@$hostname/$databasename"; */
$conn = &DB::connect($dsn);
print "date=".$conn->GetOne('select getdate()')."<br>";
@$conn->query('create table tester (id integer)');
@@ -46,7 +46,7 @@ include_once('../adodb.inc.php');
print "<h3>ADOdb</h3>";
$conn = NewADOConnection('mssql');
$conn->Connect('JAGUAR\vsdotnet','adodb','natsoft','northwind');
// $conn->debug=1;
/* $conn->debug=1; */
print "date=".$conn->GetOne('select getdate()')."<br>";
$conn->Execute('create table tester (id integer)');
print "<p>Delete</p>"; flush();
+285 -288
View File
@@ -1,288 +1,285 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
</head>
<body bgcolor=white>
<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
<div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
If you are writing an application that is used in multiple environments and
operating systems, you need to plan to support multiple databases. This article
is based on my experiences with multiple database systems, stretching from 4th
Dimension in my Mac days, to the databases I currently use, which are: Oracle,
FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies
to using SQL with Perl, Python and other programming languages, I will focus on PHP and how
the <a href="http://php.weblogs.com/adodb">ADOdb</a> database abstraction library
offers some solutions.<p></p>
<p>Most database vendors practice product lock-in. The best or fastest way to
do things is often implemented using proprietary extensions to SQL. This makes
it extremely hard to write portable SQL code that performs well under all conditions.
When the first ANSI committee got together in 1984 to standardize SQL, the database
vendors had such different implementations that they could only agree on the
core functionality of SQL. Many important application specific requirements
were not standardized, and after so many years since the ANSI effort began,
it looks as if much useful database functionality will never be standardized.
Even though ANSI-92 SQL has codified much more, we still have to implement portability
at the application level.</p>
<h3><b>Selects</b></h3>
<p>The SELECT statement has been standardized to a great degree. Nearly every
database supports the following:</p>
<p>SELECT [cols] FROM [tables]<br>
&nbsp;&nbsp;[WHERE conditions]<br>
&nbsp; [GROUP BY cols]<br>
&nbsp; [HAVING conditions] <br>
&nbsp; [ORDER BY cols]</p>
<p>But so many useful techniques can only be implemented by using proprietary
extensions. For example, when writing SQL to retrieve the first 10 rows for
paging, you could write...</p>
<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><b>Database</b></td>
<td><b>SQL Syntax</b></td>
</tr>
<tr>
<td>DB2</td>
<td>select * from table fetch first 10 rows only</td>
</tr>
<tr>
<td>Informix</td>
<td>select first 10 * from table</td>
</tr>
<tr>
<td>Microsoft SQL Server and Access</td>
<td>select top 10 * from table</td>
</tr>
<tr>
<td>MySQL and PostgreSQL</td>
<td>select * from table limit 10</td>
</tr>
<tr>
<td>Oracle 8i</td>
<td>select * from (select * from table) where rownum &lt;= 10</td>
</tr>
</table>
<p>This feature of getting a subset of data is so useful that in the PHP class
library ADOdb, we have a SelectLimit( ) function that allows you to hide the
implementation details within a function that will rewrite your SQL for you:</p>
<pre>$connection-&gt;SelectLimit('select * from table', 10);
</pre>
<p><b>Selects: Fetch Modes</b></p>
<p>PHP allows you to retrieve database records as arrays. You can choose to have
the arrays indexed by field name or number. However different low-level PHP
database drivers are inconsistent in their indexing efforts. ADOdb allows you
to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE
to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC
(using field names as an associative index).</p>
<p>The default behaviour of ADOdb varies depending on the database you are using.
For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or
ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
<p><b>Selects: Counting Records</b></p>
<p>Another problem with SELECTs is that some databases do not return the number
of rows retrieved from a select statement. This is because the highest performance
databases will return records to you even before the last record has been found.
</p>
<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate
it by buffering the rows and returning the count after all rows have been returned.
This can be disabled for performance reasons when retrieving large recordsets
by setting the global variable $ADODB_COUNTRECS = false. This variable is checked
every time a query is executed, so you can selectively choose which recordsets
to count.</p>
<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount(
) function. This will return the number of rows, or if it is not found, it will
return an estimate using SELECT COUNT(*):</p>
<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
<p><b>Selects: Locking</b> </p>
<p>SELECT statements are commonly used to implement row-level locking of tables.
Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB
do not require row-level locking because they use versioning to display data
consistent with a specific point in time.</p>
<p>Currently, I recommend encapsulating the row-level locking in a separate function,
such as RowLock($table, $where):</p>
<pre>$connection-&gt;BeginTrans( );
$connection-&gt;RowLock($table, $where); </pre>
<pre><font color=green># some operation</font></pre>
<pre>if ($ok) $connection-&gt;CommitTrans( );
else $connection-&gt;RollbackTrans( );
</pre>
<p><b>Selects: Outer Joins</b></p>
<p>Not all databases support outer joins. Furthermore the syntax for outer joins
differs dramatically between database vendors. One portable (and possibly slower)
method of implementing outer joins is using UNION.</p>
<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could
look like:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola <br> FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
<p>This can be emulated using:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br> WHERE t1.col = t2.col
UNION ALL
SELECT col1, col2, null FROM t1 <br> WHERE t1.col not in (select distinct col from t2)
</pre>
<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal
join variations. This is still incomplete and sometimes depends on the database
version you are using, but is useful as a general guideline:</p>
<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the
operator used for left outer joins (eg. '*='), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the
operator used for right outer joins (eg '=*'), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean
that if true means that ANSI-92 style outer joins are supported, or false if
not known.</p>
<h3><b>Inserts</b> </h3>
<p>When you create records, you need to generate unique id's for each record.
There are two common techniques: (1) auto-incrementing columns and (2) sequences.
</p>
<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access
and SQL Server. However most other databases do not support this feature. So
for portability, you have little choice but to use sequences. Sequences are
special functions that return a unique incrementing number every time you call
it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function.
It has takes a parameter, the sequence name. Different tables can have different
sequences. </p>
<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br> values ($id, $firstname, $lastname)&quot;);</pre>
<p>For databases that do not support sequences natively, ADOdb emulates sequences
by creating a table for every sequence.</p>
<h3><b>Binding</b></h3>
<p>Binding variables in an SQL statement is another tricky feature. Binding is
useful because it allows pre-compilation of SQL. When inserting multiple records
into a database in a loop, binding can offer a 50% (or greater) speedup. However
many databases such as Access and MySQL do not support binding natively and
there is some overhead in emulating binding. Furthermore, different databases
(specificly Oracle!) implement binding differently. My recommendation is to
use binding if your database queries are too slow, but make sure you are using
a database that supports it like Oracle. </p>
<p>ADOdb supports portable Prepare/Execute with:</p>
<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
<h2>DDL and Tuning</h2>
<p>There are database design tools such as ERWin or Dezign that allow you to generate
data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship
diagrams. Other developers such as Manuel Lemos have developed portable XML
based schemas for PHP with Metabase. I think this might suit many developers,
but I prefer to manually define the database tables. This is because for high
performance, the placement of tables and selection of the different types of
indexes has to be planned based on the number of hard disks and the i/o characteristics
of the data. This can only be done manually. Here are some tuning hints:</p>
<ul>
<li>The most important and frequently used tables deserve to be placed on their
own separate hard disks. </li>
<li>Indexes and data should be kept on different hard disks. </li>
<li>Transaction logs and rollback segments deserve their own hard disks.</li>
<li>Using Striping (RAID 5) is only useful when you rarely write to your database.
Mirroring is a better compromise between reading and writing.</li>
<li>Consider bypassing the file system and using raw disks.</li>
<li>Make sure you have asynchronous IO enabled for your database and operating
system.</li>
<li>Be prepared to waste space. You probably need at least 5 hard disks for
a high-performance database system:<br>
- 1 hard disk for the operating system and temporary data, <br>
- 1 for data,<br>
- 1 for indexes, <br>
- 1 for rollback, <br>
- 1 for transaction logs.</li>
</ul>
<h3>Data Types</h3>
<p>Stick to a few data types that are available in most databases. Char, varchar
and numeric/number are supported by most databases. Most other data types (including
integer, boolean and float) cannot be relied on being available. I recommend
using char(1) or number(1) to hold booleans. </p>
<p>Different databases have different ways of representing dates and timestamps/datetime.
ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides
DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable
to that database. Both functions accept Unix integer timestamps and date strings
in ISO format.</p>
<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
<p>We also provide functions to convert database dates to Unix timestamps:</p>
<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =&gt; unix timestamp</font></pre>
<p>The maximum length of a char/varchar field is also database specific. You can
only assume that field lengths of up to 250 characters are supported. This is
normally impractical for web based forum or content management systems. You
will need to be familiar with how databases handle large objects (LOBs). ADOdb
implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to
update fields holding Binary Large Objects (eg. pictures) and Character Large
Objects (eg. HTML articles):</p>
<pre><font color=green># for oracle </font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
<font color=green># non-oracle databases</font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
</pre>
<p>Null handling is another area where differences can occur. This is a mine-field,
because 3-value logic is tricky.
<p>In general, I avoid using nulls except for dates and default all my numeric
and character fields to 0 or the empty string. This maintains consistency with
PHP, where empty strings and zero are treated as equivalent, and avoids SQL
ambiguities when you use the ANY and EXISTS operators. However if your database
has significant amounts of missing or unknown data, using nulls might be a good
idea.
<h3><b>Stored Procedures</b></h3>
<p>Stored procedures are another problem area. Some databases allow recordsets
to be returned in a stored procedure (Microsoft SQL Server and Sybase), and
others only allow output parameters to be returned. Stored procedures sometimes
need to be wrapped in special syntax. For example, Oracle requires such code
to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators
and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors.
</p>
<p>An example of how to call a stored procedure with 2 parameters and 1 return
value follows:</p>
<pre> switch ($db->databaseType) {
case '<font color="#993300">mssql</font>':
$sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
case '<font color="#993300">oci8</font>':
$sql =
<font color="#993300"> </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
</font> break;</font>
default:
die('<font color="#993300">Unsupported feature</font>');
}
<font color="#000000"><font color="green"> # @RETVAL = SP_RUNSOMETHING @myid,@group</font>
$stmt = $db-&gt;PrepareSP($sql); <br> $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>');
$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
<font color="green"># true indicates output parameter<br> </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true);
$db-&gt;Execute($stmt); </font></pre>
<p>As you can see, the ADOdb API is the same for both databases. But the stored
procedure SQL syntax is quite different between databases and is not portable,
so be forewarned! However sometimes you have little choice as some systems only
allow data to be accessed via stored procedures. This is when the ultimate portability
solution might be the only solution: <i>treating portable SQL as a localization
exercise...</i></p>
<h3><b>SQL as a Localization Exercise</b></h3>
<p> In general to provide real portability, you will have to treat SQL coding
as a localization exercise. In PHP, it has become common to define separate
language files for English, Russian, Korean, etc. Similarly, I would suggest
you have separate Sybase, Intebase, MySQL, etc files, and conditionally include
the SQL based on the database. For example, each MySQL SQL statement would be
stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
$sqlSearchKeyword = &quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
<p>In our main PHP file:</p>
<pre><font color=green># define which database to load...</font>
<b>$database = '<font color="#993300">mysql</font>';
include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
$db = &amp;NewADOConnection($database);
$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
<font color=green># search for a keyword $word</font>
$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
<p>Note that we quote the $word variable using the qstr( ) function. This is because
each database quotes strings using different conventions.</p>
<p>
<h3>Final Thoughts</h3>
<p>The best way to ensure that you have portable SQL is to have your data tables designed using
sound principles. Learn the theory of normalization and entity-relationship diagrams and model
your data carefully. Understand how joins and indexes work and how they are used to tune performance.
<p> Visit the following page for more references on database theory and vendors:
<a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>.
Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
<p>
<font size=1>(c) 2002 John Lim.</font>
</body>
</html>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Tips on Writing Portable SQL for Multiple Databases for PHP</title>
</head>
<body bgcolor=white>
<table width=100% border=0><tr><td><h2>Tips on Writing Portable SQL &nbsp;</h2></td><td>
<div align=right><img src="cute_icons_for_site/adodb.gif"></div></td></tr></table>
If you are writing an application that is used in multiple environments and
operating systems, you need to plan to support multiple databases. This article
is based on my experiences with multiple database systems, stretching from 4th
Dimension in my Mac days, to the databases I currently use, which are: Oracle,
FoxPro, Access, MS SQL Server and MySQL. Although most of the advice here applies
to using SQL with Perl, Python and other programming languages, I will focus on PHP and how
the <a href="http://php.weblogs.com/adodb">ADOdb</a> database abstraction library
offers some solutions.<p></p>
<p>Most database vendors practice product lock-in. The best or fastest way to
do things is often implemented using proprietary extensions to SQL. This makes
it extremely hard to write portable SQL code that performs well under all conditions.
When the first ANSI committee got together in 1984 to standardize SQL, the database
vendors had such different implementations that they could only agree on the
core functionality of SQL. Many important application specific requirements
were not standardized, and after so many years since the ANSI effort began,
it looks as if much useful database functionality will never be standardized.
Even though ANSI-92 SQL has codified much more, we still have to implement portability
at the application level.</p>
<h3><b>Selects</b></h3>
<p>The SELECT statement has been standardized to a great degree. Nearly every
database supports the following:</p>
<p>SELECT [cols] FROM [tables]<br>
&nbsp;&nbsp;[WHERE conditions]<br>
&nbsp; [GROUP BY cols]<br>
&nbsp; [HAVING conditions] <br>
&nbsp; [ORDER BY cols]</p>
<p>But so many useful techniques can only be implemented by using proprietary
extensions. For example, when writing SQL to retrieve the first 10 rows for
paging, you could write...</p>
<table width="80%" border="1" cellspacing="0" cellpadding="0" align="center">
<tr>
<td><b>Database</b></td>
<td><b>SQL Syntax</b></td>
</tr>
<tr>
<td>DB2</td>
<td>select * from table fetch first 10 rows only</td>
</tr>
<tr>
<td>Informix</td>
<td>select first 10 * from table</td>
</tr>
<tr>
<td>Microsoft SQL Server and Access</td>
<td>select top 10 * from table</td>
</tr>
<tr>
<td>MySQL and PostgreSQL</td>
<td>select * from table limit 10</td>
</tr>
<tr>
<td>Oracle 8i</td>
<td>select * from (select * from table) where rownum &lt;= 10</td>
</tr>
</table>
<p>This feature of getting a subset of data is so useful that in the PHP class
library ADOdb, we have a SelectLimit( ) function that allows you to hide the
implementation details within a function that will rewrite your SQL for you:</p>
<pre>$connection-&gt;SelectLimit('select * from table', 10);
</pre>
<p><b>Selects: Fetch Modes</b></p>
<p>PHP allows you to retrieve database records as arrays. You can choose to have
the arrays indexed by field name or number. However different low-level PHP
database drivers are inconsistent in their indexing efforts. ADOdb allows you
to determine your prefered mode. You set this by setting the variable $ADODB_FETCH_MODE
to either of the constants ADODB_FETCH_NUM (for numeric indexes) or ADODB_FETCH_ASSOC
(using field names as an associative index).</p>
<p>The default behaviour of ADOdb varies depending on the database you are using.
For consistency, set the fetch mode to either ADODB_FETCH_NUM (for speed) or
ADODB_FETCH_ASSOC (for convenience) at the beginning of your code. </p>
<p><b>Selects: Counting Records</b></p>
<p>Another problem with SELECTs is that some databases do not return the number
of rows retrieved from a select statement. This is because the highest performance
databases will return records to you even before the last record has been found.
</p>
<p>In ADOdb, RecordCount( ) returns the number of rows returned, or will emulate
it by buffering the rows and returning the count after all rows have been returned.
This can be disabled for performance reasons when retrieving large recordsets
by setting the global variable $ADODB_COUNTRECS = false. This variable is checked
every time a query is executed, so you can selectively choose which recordsets
to count.</p>
<p>If you prefer to set $ADODB_COUNTRECS = false, ADOdb still has the PO_RecordCount(
) function. This will return the number of rows, or if it is not found, it will
return an estimate using SELECT COUNT(*):</p>
<pre>$rs = $db-&gt;Execute(&quot;select * from table where state=$state&quot;);
$numrows = $rs-&gt;PO_RecordCount('table', &quot;state=$state&quot;);</pre>
<p><b>Selects: Locking</b> </p>
<p>SELECT statements are commonly used to implement row-level locking of tables.
Other databases such as Oracle, Interbase, PostgreSQL and MySQL with InnoDB
do not require row-level locking because they use versioning to display data
consistent with a specific point in time.</p>
<p>Currently, I recommend encapsulating the row-level locking in a separate function,
such as RowLock($table, $where):</p>
<pre>$connection-&gt;BeginTrans( );
$connection-&gt;RowLock($table, $where); </pre>
<pre><font color=green># some operation</font></pre>
<pre>if ($ok) $connection-&gt;CommitTrans( );
else $connection-&gt;RollbackTrans( );
</pre>
<p><b>Selects: Outer Joins</b></p>
<p>Not all databases support outer joins. Furthermore the syntax for outer joins
differs dramatically between database vendors. One portable (and possibly slower)
method of implementing outer joins is using UNION.</p>
<p>For example, an ANSI-92 left outer join between two tables t1 and t2 could
look like:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola <br> FROM t1 <i>LEFT JOIN</i> t2 ON t1.col = t2.col</pre>
<p>This can be emulated using:</p>
<pre>SELECT t1.col1, t1.col2, t2.cola FROM t1, t2 <br> WHERE t1.col = t2.col
UNION ALL
SELECT col1, col2, null FROM t1 <br> WHERE t1.col not in (select distinct col from t2)
</pre>
<p>Since ADOdb 2.13, we provide some hints in the connection object as to legal
join variations. This is still incomplete and sometimes depends on the database
version you are using, but is useful as a general guideline:</p>
<p><font face="Courier New, Courier, mono">$conn-&gt;leftOuter</font>: holds the
operator used for left outer joins (eg. '*='), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;rightOuter</font>: holds the
operator used for right outer joins (eg '=*'), or false if not known or not
available.<br>
<font face="Courier New, Courier, mono">$conn-&gt;ansiOuter</font>: boolean
that if true means that ANSI-92 style outer joins are supported, or false if
not known.</p>
<h3><b>Inserts</b> </h3>
<p>When you create records, you need to generate unique id's for each record.
There are two common techniques: (1) auto-incrementing columns and (2) sequences.
</p>
<p>Auto-incrementing columns are supported by MySQL, Sybase and Microsoft Access
and SQL Server. However most other databases do not support this feature. So
for portability, you have little choice but to use sequences. Sequences are
special functions that return a unique incrementing number every time you call
it, suitable to be used as database keys. In ADOdb, we use the GenID( ) function.
It has takes a parameter, the sequence name. Different tables can have different
sequences. </p>
<pre>$id = $connection-&gt;GenID('sequence_name');<br>$connection-&gt;Execute(&quot;insert into table (id, firstname, lastname) <br> values ($id, $firstname, $lastname)&quot;);</pre>
<p>For databases that do not support sequences natively, ADOdb emulates sequences
by creating a table for every sequence.</p>
<h3><b>Binding</b></h3>
<p>Binding variables in an SQL statement is another tricky feature. Binding is
useful because it allows pre-compilation of SQL. When inserting multiple records
into a database in a loop, binding can offer a 50% (or greater) speedup. However
many databases such as Access and MySQL do not support binding natively and
there is some overhead in emulating binding. Furthermore, different databases
(specificly Oracle!) implement binding differently. My recommendation is to
use binding if your database queries are too slow, but make sure you are using
a database that supports it like Oracle. </p>
<p>ADOdb supports portable Prepare/Execute with:</p>
<pre>$stmt = $db-&gt;Prepare('select * from customers where custid=? and state=?');
$rs = $db-&gt;Execute($stmt, array($id,'New York'));</pre>
<h2>DDL and Tuning</h2>
There are database design tools such as ERWin or Dezign that allow you to generate data definition language commands such as ALTER TABLE or CREATE INDEX from Entity-Relationship diagrams.
<p>
However if you prefer to use a PHP-based table creation scheme, adodb provides you with this feature. Here is the code to generate the SQL to create a table with:
<ol>
<li> Auto-increment primary key 'ID', </li>
<li>The person's 'NAME' VARCHAR(32) NOT NULL and defaults to '', </li>
<li>The date and time of record creation 'CREATED', </li>
<li> The person's 'AGE', defaulting to 0, type NUMERIC(16). </li>
</ol>
<p>
Also create a compound index consisting of 'NAME' and 'AGE':
<pre>
$datadict = <strong>NewDataDictionary</strong>($connection);
$flds = "
<font color="#660000"> ID I AUTOINCREMENT PRIMARY,
NAME C(32) DEFAULT '' NOTNULL,
CREATED T DEFTIMESTAMP,
AGE N(16) DEFAULT 0</font>
";
$sql1 = $datadict-><strong>CreateTableSQL</strong>('tabname', $flds);
$sql2 = $datadict-><strong>CreateIndexSQL</strong>('idx_name_age', 'tabname', 'NAME,AGE');
</pre>
<h3>Data Types</h3>
<p>Stick to a few data types that are available in most databases. Char, varchar
and numeric/number are supported by most databases. Most other data types (including
integer, boolean and float) cannot be relied on being available. I recommend
using char(1) or number(1) to hold booleans. </p>
<p>Different databases have different ways of representing dates and timestamps/datetime.
ADOdb attempts to display all dates in ISO (YYYY-MM-DD) format. ADOdb also provides
DBDate( ) and DBTimeStamp( ) to convert dates to formats that are acceptable
to that database. Both functions accept Unix integer timestamps and date strings
in ISO format.</p>
<pre>$date1 = $connection-&gt;DBDate(time( ));<br>$date2 = $connection-&gt;DBTimeStamp('2002-02-23 13:03:33');</pre>
<p>We also provide functions to convert database dates to Unix timestamps:</p>
<pre>$unixts = $recordset-&gt;UnixDate('#2002-02-30#'); <font color="green"># MS Access date =&gt; unix timestamp</font></pre>
<p>The maximum length of a char/varchar field is also database specific. You can
only assume that field lengths of up to 250 characters are supported. This is
normally impractical for web based forum or content management systems. You
will need to be familiar with how databases handle large objects (LOBs). ADOdb
implements two functions, UpdateBlob( ) and UpdateClob( ) that allow you to
update fields holding Binary Large Objects (eg. pictures) and Character Large
Objects (eg. HTML articles):</p>
<pre><font color=green># for oracle </font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1,empty_blob())');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
<font color=green># non-oracle databases</font>
$conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
$conn->UpdateBlob('blobtable','blobcol',$blobvalue,'id=1');
</pre>
<p>Null handling is another area where differences can occur. This is a mine-field,
because 3-value logic is tricky.
<p>In general, I avoid using nulls except for dates and default all my numeric
and character fields to 0 or the empty string. This maintains consistency with
PHP, where empty strings and zero are treated as equivalent, and avoids SQL
ambiguities when you use the ANY and EXISTS operators. However if your database
has significant amounts of missing or unknown data, using nulls might be a good
idea.
<h3><b>Stored Procedures</b></h3>
<p>Stored procedures are another problem area. Some databases allow recordsets
to be returned in a stored procedure (Microsoft SQL Server and Sybase), and
others only allow output parameters to be returned. Stored procedures sometimes
need to be wrapped in special syntax. For example, Oracle requires such code
to be wrapped in an anonymous block with BEGIN and END. Also internal sql operators
and functions such as +, ||, TRIM( ), SUBSTR( ) or INSTR( ) vary between vendors.
</p>
<p>An example of how to call a stored procedure with 2 parameters and 1 return
value follows:</p>
<pre> switch ($db->databaseType) {
case '<font color="#993300">mssql</font>':
$sql = <font color="#000000"><font color="#993333">'<font color="#993300">SP_RUNSOMETHING</font>'</font></font>; break;
case '<font color="#993300">oci8</font>':
$sql =
<font color="#993300"> </font><font color="#000000"><font color="#993300">&quot;declare RETVAL integer;begin :RETVAL := </font><font color="#000000"><font color="#993333"><font color="#993300">SP_RUNSOMETHING</font></font></font><font color="#993300">(:myid,:group);end;&quot;;
</font> break;</font>
default:
die('<font color="#993300">Unsupported feature</font>');
}
<font color="#000000"><font color="green"> # @RETVAL = SP_RUNSOMETHING @myid,@group</font>
$stmt = $db-&gt;PrepareSP($sql); <br> $db-&gt;Parameter($stmt,$id,'<font color="#993300">myid</font>');
$db-&gt;Parameter($stmt,$group,'<font color="#993300">group</font>');
<font color="green"># true indicates output parameter<br> </font>$db-&gt;Parameter($stmt,$ret,'<font color="#993300">RETVAL</font>',true);
$db-&gt;Execute($stmt); </font></pre>
<p>As you can see, the ADOdb API is the same for both databases. But the stored
procedure SQL syntax is quite different between databases and is not portable,
so be forewarned! However sometimes you have little choice as some systems only
allow data to be accessed via stored procedures. This is when the ultimate portability
solution might be the only solution: <i>treating portable SQL as a localization
exercise...</i></p>
<h3><b>SQL as a Localization Exercise</b></h3>
<p> In general to provide real portability, you will have to treat SQL coding
as a localization exercise. In PHP, it has become common to define separate
language files for English, Russian, Korean, etc. Similarly, I would suggest
you have separate Sybase, Intebase, MySQL, etc files, and conditionally include
the SQL based on the database. For example, each MySQL SQL statement would be
stored in a separate variable, in a file called 'mysql-lang.inc.php'.</p>
<pre>$sqlGetPassword = '<font color="#993300">select password from users where userid=%s</font>';
$sqlSearchKeyword = &quot;<font color="#993300">SELECT * FROM articles WHERE match (title,body) against (%s</font>)&quot;;</pre>
<p>In our main PHP file:</p>
<pre><font color=green># define which database to load...</font>
<b>$database = '<font color="#993300">mysql</font>';
include_once(&quot;<font color="#993300">$database-lang.inc.php</font>&quot;);</b>
$db = &amp;NewADOConnection($database);
$db->PConnect(...) or die('<font color="#993300">Failed to connect to database</font>');
<font color=green># search for a keyword $word</font>
$rs = $db-&gt;Execute(sprintf($sqlSearchKeyWord,$db-&gt;qstr($word)));</pre>
<p>Note that we quote the $word variable using the qstr( ) function. This is because
each database quotes strings using different conventions.</p>
<p>
<h3>Final Thoughts</h3>
<p>The best way to ensure that you have portable SQL is to have your data tables designed using
sound principles. Learn the theory of normalization and entity-relationship diagrams and model
your data carefully. Understand how joins and indexes work and how they are used to tune performance.
<p> Visit the following page for more references on database theory and vendors:
<a href="http://php.weblogs.com/sql_tutorial">http://php.weblogs.com/sql_tutorial</a>.
Also read this article on <a href=http://phplens.com/lens/php-book/optimizing-debugging-php.php>Optimizing PHP</a>.
<p>
<font size=1>(c) 2002 John Lim.</font>
</body>
</html>
+129 -129
View File
@@ -1,130 +1,130 @@
<?php
/**
* @version V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Code to export recordsets in several formats:
*
* AS VARIABLE
* $s = rs2csv($rs); # comma-separated values
* $s = rs2tab($rs); # tab delimited
*
* TO A FILE
* $f = fopen($path,'w');
* rs2csvfile($rs,$f);
* fclose($f);
*
* TO STDOUT
* rs2csvout($rs);
*/
// returns a recordset as a csv string
function rs2csv(&$rs,$addtitles=true)
{
return _adodb_export($rs,',',',',false,$addtitles);
}
// writes recordset to csv file
function rs2csvfile(&$rs,$fp,$addtitles=true)
{
_adodb_export($rs,',',',',$fp,$addtitles);
}
// write recordset as csv string to stdout
function rs2csvout(&$rs,$addtitles=true)
{
$fp = fopen('php://stdout','wb');
_adodb_export($rs,',',',',true,$addtitles);
fclose($fp);
}
function rs2tab(&$rs,$addtitles=true)
{
return _adodb_export($rs,"\t",',',false,$addtitles);
}
// to file pointer
function rs2tabfile(&$rs,$fp,$addtitles=true)
{
_adodb_export($rs,"\t",',',$fp,$addtitles);
}
// to stdout
function rs2tabout(&$rs,$addtitles=true)
{
$fp = fopen('php://stdout','wb');
_adodb_export($rs,"\t",' ',true,$addtitles);
fclose($fp);
}
function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
{
if (!$rs) return '';
//----------
// CONSTANTS
$NEWLINE = "\r\n";
$BUFLINES = 100;
$escquotequote = $escquote.$quote;
$s = '';
if ($addtitles) {
$fieldTypes = $rs->FieldTypesArray();
foreach($fieldTypes as $o) {
$v = $o->name;
if ($escquote) $v = str_replace($quote,$escquotequote,$v);
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
$elements[] = $v;
}
$s .= implode($sep, $elements).$NEWLINE;
}
$hasNumIndex = isset($rs->fields[0]);
$line = 0;
$max = $rs->FieldCount();
while (!$rs->EOF) {
$elements = array();
$i = 0;
if ($hasNumIndex) {
for ($j=0; $j < $max; $j++) {
$v = trim($rs->fields[$j]);
if ($escquote) $v = str_replace($quote,$escquotequote,$v);
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
else $elements[] = $v;
}
} else { // ASSOCIATIVE ARRAY
foreach($rs->fields as $v) {
if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
else $elements[] = $v;
}
}
$s .= implode($sep, $elements).$NEWLINE;
$rs->MoveNext();
$line += 1;
if ($fp && ($line % $BUFLINES) == 0) {
if ($fp === true) echo $s;
else fwrite($fp,$s);
$s = '';
}
}
if ($fp) {
if ($fp === true) echo $s;
else fwrite($fp,$s);
$s = '';
}
return $s;
}
<?php
/**
* @version V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
* Released under both BSD license and Lesser GPL library license.
* Whenever there is any discrepancy between the two licenses,
* the BSD license will take precedence.
*
* Code to export recordsets in several formats:
*
* AS VARIABLE
* $s = rs2csv($rs); # comma-separated values
* $s = rs2tab($rs); # tab delimited
*
* TO A FILE
* $f = fopen($path,'w');
* rs2csvfile($rs,$f);
* fclose($f);
*
* TO STDOUT
* rs2csvout($rs);
*/
/* returns a recordset as a csv string */
function rs2csv(&$rs,$addtitles=true)
{
return _adodb_export($rs,',',',',false,$addtitles);
}
/* writes recordset to csv file */
function rs2csvfile(&$rs,$fp,$addtitles=true)
{
_adodb_export($rs,',',',',$fp,$addtitles);
}
/* write recordset as csv string to stdout */
function rs2csvout(&$rs,$addtitles=true)
{
$fp = fopen('php:/* stdout','wb'); */
_adodb_export($rs,',',',',true,$addtitles);
fclose($fp);
}
function rs2tab(&$rs,$addtitles=true)
{
return _adodb_export($rs,"\t",',',false,$addtitles);
}
/* to file pointer */
function rs2tabfile(&$rs,$fp,$addtitles=true)
{
_adodb_export($rs,"\t",',',$fp,$addtitles);
}
/* to stdout */
function rs2tabout(&$rs,$addtitles=true)
{
$fp = fopen('php:/* stdout','wb'); */
_adodb_export($rs,"\t",' ',true,$addtitles);
fclose($fp);
}
function _adodb_export(&$rs,$sep,$sepreplace,$fp=false,$addtitles=true,$quote = '"',$escquote = '"',$replaceNewLine = ' ')
{
if (!$rs) return '';
/* ---------- */
/* CONSTANTS */
$NEWLINE = "\r\n";
$BUFLINES = 100;
$escquotequote = $escquote.$quote;
$s = '';
if ($addtitles) {
$fieldTypes = $rs->FieldTypesArray();
foreach($fieldTypes as $o) {
$v = $o->name;
if ($escquote) $v = str_replace($quote,$escquotequote,$v);
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
$elements[] = $v;
}
$s .= implode($sep, $elements).$NEWLINE;
}
$hasNumIndex = isset($rs->fields[0]);
$line = 0;
$max = $rs->FieldCount();
while (!$rs->EOF) {
$elements = array();
$i = 0;
if ($hasNumIndex) {
for ($j=0; $j < $max; $j++) {
$v = trim($rs->fields[$j]);
if ($escquote) $v = str_replace($quote,$escquotequote,$v);
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
else $elements[] = $v;
}
} else { /* ASSOCIATIVE ARRAY */
foreach($rs->fields as $v) {
if ($escquote) $v = str_replace($quote,$escquotequote,trim($v));
$v = strip_tags(str_replace("\n",$replaceNewLine,str_replace($sep,$sepreplace,$v)));
if (strpos($v,$sep) !== false || strpos($v,$quote) !== false) $elements[] = "$quote$v$quote";
else $elements[] = $v;
}
}
$s .= implode($sep, $elements).$NEWLINE;
$rs->MoveNext();
$line += 1;
if ($fp && ($line % $BUFLINES) == 0) {
if ($fp === true) echo $s;
else fwrite($fp,$s);
$s = '';
}
}
if ($fp) {
if ($fp === true) echo $s;
else fwrite($fp,$s);
$s = '';
}
return $s;
}
?>
+154 -154
View File
@@ -1,154 +1,154 @@
<?php
/*
V3.40 7 April 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Some pretty-printing by Chris Oxenreider <[email protected]>
*/
// specific code for tohtml
GLOBAL $gSQLMaxRows,$gSQLBlockRows;
$gSQLMaxRows = 1000; // max no of rows to download
$gSQLBlockRows=20; // max no of rows per table block
// RecordSet to HTML Table
//------------------------------------------------------------
// Convert a recordset to a html table. Multiple tables are generated
// if the number of rows is > $gSQLBlockRows. This is because
// web browsers normally require the whole table to be downloaded
// before it can be rendered, so we break the output into several
// smaller faster rendering tables.
//
// $rs: the recordset
// $ztabhtml: the table tag attributes (optional)
// $zheaderarray: contains the replacement strings for the headers (optional)
//
// USAGE:
// include('adodb.inc.php');
// $db = ADONewConnection('mysql');
// $db->Connect('mysql','userid','password','database');
// $rs = $db->Execute('select col1,col2,col3 from table');
// rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3'));
// $rs->Close();
//
// RETURNS: number of rows displayed
function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true)
{
$s ='';$rows=0;$docnt = false;
GLOBAL $gSQLMaxRows,$gSQLBlockRows;
if (!$rs) {
printf(ADODB_BAD_RS,'rs2html');
return false;
}
if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'";
//else $docnt = true;
$typearr = array();
$ncols = $rs->FieldCount();
$hdr = "<TABLE COLS=$ncols $ztabhtml>\n\n";
for ($i=0; $i < $ncols; $i++) {
$field = $rs->FetchField($i);
if ($zheaderarray) $fname = $zheaderarray[$i];
else $fname = htmlspecialchars($field->name);
$typearr[$i] = $rs->MetaType($field->type,$field->max_length);
//print " $field->name $field->type $typearr[$i] ";
if (strlen($fname)==0) $fname = '&nbsp;';
$hdr .= "<TH>$fname</TH>";
}
print $hdr."\n\n";
// smart algorithm - handles ADODB_FETCH_MODE's correctly!
$numoffset = isset($rs->fields[0]);
while (!$rs->EOF) {
$s .= "<TR valign=top>\n";
for ($i=0, $v=($numoffset) ? $rs->fields[0] : reset($rs->fields);
$i < $ncols;
$i++, $v = ($numoffset) ? @$rs->fields[$i] : next($rs->fields)) {
$type = $typearr[$i];
switch($type) {
case 'T':
$s .= " <TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";
break;
case 'D':
$s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";
break;
case 'I':
case 'N':
$s .= " <TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";
break;
default:
if ($htmlspecialchars) $v = htmlspecialchars($v);
$s .= " <TD>". str_replace("\n",'<br>',stripslashes((trim($v)))) ."&nbsp;</TD>\n";
}
} // for
$s .= "</TR>\n\n";
$rows += 1;
if ($rows >= $gSQLMaxRows) {
$rows = "<p>Truncated at $gSQLMaxRows</p>";
break;
} // switch
$rs->MoveNext();
// additional EOF check to prevent a widow header
if (!$rs->EOF && $rows % $gSQLBlockRows == 0) {
//if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP
print $s . "</TABLE>\n\n";
$s = $hdr;
}
} // while
print $s."</TABLE>\n\n";
if ($docnt) print "<H2>".$rows." Rows</H2>";
return $rows;
}
// pass in 2 dimensional array
function arr2html(&$arr,$ztabhtml='',$zheaderarray='')
{
if (!$ztabhtml) $ztabhtml = 'BORDER=1';
$s = "<TABLE $ztabhtml>";//';print_r($arr);
if ($zheaderarray) {
$s .= '<TR>';
for ($i=0; $i<sizeof($zheaderarray); $i++) {
$s .= " <TH>{$zheaderarray[$i]}</TH>\n";
}
$s .= "\n</TR>";
}
for ($i=0; $i<sizeof($arr); $i++) {
$s .= '<TR>';
$a = &$arr[$i];
if (is_array($a))
for ($j=0; $j<sizeof($a); $j++) {
$val = $a[$j];
if (empty($val)) $val = '&nbsp;';
$s .= " <TD>$val</TD>\n";
}
else if ($a) {
$s .= ' <TD>'.$a."</TD>\n";
} else $s .= " <TD>&nbsp;</TD>\n";
$s .= "\n</TR>\n";
}
$s .= '</TABLE>';
print $s;
}
<?php
/*
V3.60 16 June 2003 (c) 2000-2003 John Lim ([email protected]). All rights reserved.
Released under both BSD license and Lesser GPL library license.
Whenever there is any discrepancy between the two licenses,
the BSD license will take precedence.
Some pretty-printing by Chris Oxenreider <[email protected]>
*/
/* specific code for tohtml */
GLOBAL $gSQLMaxRows,$gSQLBlockRows;
$gSQLMaxRows = 1000; /* max no of rows to download */
$gSQLBlockRows=20; /* max no of rows per table block */
/* RecordSet to HTML Table */
/* ------------------------------------------------------------ */
/* Convert a recordset to a html table. Multiple tables are generated */
/* if the number of rows is > $gSQLBlockRows. This is because */
/* web browsers normally require the whole table to be downloaded */
/* before it can be rendered, so we break the output into several */
/* smaller faster rendering tables. */
/* */
/* $rs: the recordset */
/* $ztabhtml: the table tag attributes (optional) */
/* $zheaderarray: contains the replacement strings for the headers (optional) */
/* */
/* USAGE: */
/* include('adodb.inc.php'); */
/* $db = ADONewConnection('mysql'); */
/* $db->Connect('mysql','userid','password','database'); */
/* $rs = $db->Execute('select col1,col2,col3 from table'); */
/* rs2html($rs, 'BORDER=2', array('Title1', 'Title2', 'Title3')); */
/* $rs->Close(); */
/* */
/* RETURNS: number of rows displayed */
function rs2html(&$rs,$ztabhtml=false,$zheaderarray=false,$htmlspecialchars=true)
{
$s ='';$rows=0;$docnt = false;
GLOBAL $gSQLMaxRows,$gSQLBlockRows;
if (!$rs) {
printf(ADODB_BAD_RS,'rs2html');
return false;
}
if (! $ztabhtml) $ztabhtml = "BORDER='1' WIDTH='98%'";
/* else $docnt = true; */
$typearr = array();
$ncols = $rs->FieldCount();
$hdr = "<TABLE COLS=$ncols $ztabhtml>\n\n";
for ($i=0; $i < $ncols; $i++) {
$field = $rs->FetchField($i);
if ($zheaderarray) $fname = $zheaderarray[$i];
else $fname = htmlspecialchars($field->name);
$typearr[$i] = $rs->MetaType($field->type,$field->max_length);
/* print " $field->name $field->type $typearr[$i] "; */
if (strlen($fname)==0) $fname = '&nbsp;';
$hdr .= "<TH>$fname</TH>";
}
print $hdr."\n\n";
/* smart algorithm - handles ADODB_FETCH_MODE's correctly! */
$numoffset = isset($rs->fields[0]);
while (!$rs->EOF) {
$s .= "<TR valign=top>\n";
for ($i=0, $v=($numoffset) ? $rs->fields[0] : reset($rs->fields);
$i < $ncols;
$i++, $v = ($numoffset) ? @$rs->fields[$i] : next($rs->fields)) {
$type = $typearr[$i];
switch($type) {
case 'T':
$s .= " <TD>".$rs->UserTimeStamp($v,"D d, M Y, h:i:s") ."&nbsp;</TD>\n";
break;
case 'D':
$s .= " <TD>".$rs->UserDate($v,"D d, M Y") ."&nbsp;</TD>\n";
break;
case 'I':
case 'N':
$s .= " <TD align=right>".stripslashes((trim($v))) ."&nbsp;</TD>\n";
break;
default:
if ($htmlspecialchars) $v = htmlspecialchars($v);
$s .= " <TD>". str_replace("\n",'<br>',stripslashes((trim($v)))) ."&nbsp;</TD>\n";
}
} /* for */
$s .= "</TR>\n\n";
$rows += 1;
if ($rows >= $gSQLMaxRows) {
$rows = "<p>Truncated at $gSQLMaxRows</p>";
break;
} /* switch */
$rs->MoveNext();
/* additional EOF check to prevent a widow header */
if (!$rs->EOF && $rows % $gSQLBlockRows == 0) {
/* if (connection_aborted()) break;// not needed as PHP aborts script, unlike ASP */
print $s . "</TABLE>\n\n";
$s = $hdr;
}
} /* while */
print $s."</TABLE>\n\n";
if ($docnt) print "<H2>".$rows." Rows</H2>";
return $rows;
}
/* pass in 2 dimensional array */
function arr2html(&$arr,$ztabhtml='',$zheaderarray='')
{
if (!$ztabhtml) $ztabhtml = 'BORDER=1';
$s = "<TABLE $ztabhtml>";/* ';print_r($arr); */
if ($zheaderarray) {
$s .= '<TR>';
for ($i=0; $i<sizeof($zheaderarray); $i++) {
$s .= " <TH>{$zheaderarray[$i]}</TH>\n";
}
$s .= "\n</TR>";
}
for ($i=0; $i<sizeof($arr); $i++) {
$s .= '<TR>';
$a = &$arr[$i];
if (is_array($a))
for ($j=0; $j<sizeof($a); $j++) {
$val = $a[$j];
if (empty($val)) $val = '&nbsp;';
$s .= " <TD>$val</TD>\n";
}
else if ($a) {
$s .= ' <TD>'.$a."</TD>\n";
} else $s .= " <TD>&nbsp;</TD>\n";
$s .= "\n</TR>\n";
}
$s .= '</TABLE>';
print $s;
}