3 V5.14 8 Sept 2011 (c) 2000-2011 John Lim (jlim#natsoft.com). All rights reserved.
4 Released under both BSD license and Lesser GPL library license.
5 Whenever there is any discrepancy between the two licenses,
6 the BSD license will take precedence.
7 Set tabs to 4 for best viewing.
9 Latest version is available at http://adodb.sourceforge.net
11 Requires ODBC. Works on Windows and Unix.
13 // security - hide paths
14 if (!defined('ADODB_DIR')) die();
16 define("_ADODB_ODBC_LAYER", 2 );
18 /*--------------------------------------------------------------------------------------
19 --------------------------------------------------------------------------------------*/
22 class ADODB_odbc
extends ADOConnection
{
23 var $databaseType = "odbc";
24 var $fmtDate = "'Y-m-d'";
25 var $fmtTimeStamp = "'Y-m-d, h:i:sA'";
26 var $replaceQuote = "''"; // string to use to replace quotes
27 var $dataProvider = "odbc";
28 var $hasAffectedRows = true;
29 var $binmode = ODBC_BINMODE_RETURN
;
30 var $useFetchArray = false; // setting this to true will make array elements in FETCH_ASSOC mode case-sensitive
31 // breaking backward-compat
32 //var $longreadlen = 8000; // default number of chars to return for a Blob/Long field
33 var $_bindInputArray = false;
34 var $curmode = SQL_CUR_USE_DRIVER
; // See sqlext.h, SQL_CUR_DEFAULT == SQL_CUR_USE_DRIVER == 2L
35 var $_genSeqSQL = "create table %s (id integer)";
36 var $_autocommit = true;
37 var $_haserrorfunctions = true;
38 var $_has_stupid_odbc_fetch_api_change = true;
39 var $_lastAffectedRows = 0;
40 var $uCaseTables = true; // for meta* functions, uppercase table names
44 $this->_haserrorfunctions
= ADODB_PHPVER
>= 0x4050;
45 $this->_has_stupid_odbc_fetch_api_change
= ADODB_PHPVER
>= 0x4200;
48 // returns true or false
49 function _connect($argDSN, $argUsername, $argPassword, $argDatabasename)
53 if (!function_exists('odbc_connect')) return null;
55 if ($this->debug
&& $argDatabasename && $this->databaseType
!= 'vfp') {
56 ADOConnection
::outp("For odbc Connect(), $argDatabasename is not used. Place dsn in 1st parameter.");
58 if (isset($php_errormsg)) $php_errormsg = '';
59 if ($this->curmode
=== false) $this->_connectionID
= odbc_connect($argDSN,$argUsername,$argPassword);
60 else $this->_connectionID
= odbc_connect($argDSN,$argUsername,$argPassword,$this->curmode
);
61 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
62 if (isset($this->connectStmt
)) $this->Execute($this->connectStmt
);
64 return $this->_connectionID
!= false;
67 // returns true or false
68 function _pconnect($argDSN, $argUsername, $argPassword, $argDatabasename)
72 if (!function_exists('odbc_connect')) return null;
74 if (isset($php_errormsg)) $php_errormsg = '';
75 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
76 if ($this->debug
&& $argDatabasename) {
77 ADOConnection
::outp("For odbc PConnect(), $argDatabasename is not used. Place dsn in 1st parameter.");
79 // print "dsn=$argDSN u=$argUsername p=$argPassword<br>"; flush();
80 if ($this->curmode
=== false) $this->_connectionID
= odbc_connect($argDSN,$argUsername,$argPassword);
81 else $this->_connectionID
= odbc_pconnect($argDSN,$argUsername,$argPassword,$this->curmode
);
83 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
84 if ($this->_connectionID
&& $this->autoRollback
) @odbc_rollback
($this->_connectionID
);
85 if (isset($this->connectStmt
)) $this->Execute($this->connectStmt
);
87 return $this->_connectionID
!= false;
94 if (!empty($this->host
) && ADODB_PHPVER
>= 0x4300) {
95 $dsn = strtoupper($this->host
);
99 if (!function_exists('odbc_data_source')) return false;
103 $rez = @odbc_data_source
($this->_connectionID
,
104 $first ? SQL_FETCH_FIRST
: SQL_FETCH_NEXT
);
106 if (!is_array($rez)) break;
107 if (strtoupper($rez['server']) == $dsn) {
112 if (!$found) return ADOConnection
::ServerInfo();
113 if (!isset($rez['version'])) $rez['version'] = '';
116 return ADOConnection
::ServerInfo();
121 function CreateSequence($seqname='adodbseq',$start=1)
123 if (empty($this->_genSeqSQL
)) return false;
124 $ok = $this->Execute(sprintf($this->_genSeqSQL
,$seqname));
125 if (!$ok) return false;
127 return $this->Execute("insert into $seqname values($start)");
130 var $_dropSeqSQL = 'drop table %s';
131 function DropSequence($seqname)
133 if (empty($this->_dropSeqSQL
)) return false;
134 return $this->Execute(sprintf($this->_dropSeqSQL
,$seqname));
138 This algorithm is not very efficient, but works even if table locking
141 Will return false if unable to generate an ID after $MAXLOOPS attempts.
143 function GenID($seq='adodbseq',$start=1)
145 // if you have to modify the parameter below, your database is overloaded,
146 // or you need to implement generation of id's yourself!
149 while (--$MAXLOOPS>=0) {
150 $num = $this->GetOne("select id from $seq");
151 if ($num === false) {
152 $this->Execute(sprintf($this->_genSeqSQL
,$seq));
155 $ok = $this->Execute("insert into $seq values($start)");
156 if (!$ok) return false;
158 $this->Execute("update $seq set id=id+1 where id=$num");
160 if ($this->affected_rows() > 0) {
164 } elseif ($this->affected_rows() == 0) {
165 // some drivers do not return a valid value => try with another method
166 $value = $this->GetOne("select id from $seq");
167 if ($value == $num +
1) {
172 if ($fn = $this->raiseErrorFn
) {
173 $fn($this->databaseType
,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num);
181 if ($this->_haserrorfunctions
) {
182 if ($this->_errorMsg
!== false) return $this->_errorMsg
;
183 if (empty($this->_connectionID
)) return @odbc_errormsg
();
184 return @odbc_errormsg
($this->_connectionID
);
185 } else return ADOConnection
::ErrorMsg();
191 if ($this->_haserrorfunctions
) {
192 if ($this->_errorCode
!== false) {
193 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
194 return (strlen($this->_errorCode
)<=2) ?
0 : $this->_errorCode
;
197 if (empty($this->_connectionID
)) $e = @odbc_error
();
198 else $e = @odbc_error
($this->_connectionID
);
200 // bug in 4.0.6, error number can be corrupted string (should be 6 digits)
201 // so we check and patch
202 if (strlen($e)<=2) return 0;
204 } else return ADOConnection
::ErrorNo();
209 function BeginTrans()
211 if (!$this->hasTransactions
) return false;
212 if ($this->transOff
) return true;
213 $this->transCnt +
= 1;
214 $this->_autocommit
= false;
215 return odbc_autocommit($this->_connectionID
,false);
218 function CommitTrans($ok=true)
220 if ($this->transOff
) return true;
221 if (!$ok) return $this->RollbackTrans();
222 if ($this->transCnt
) $this->transCnt
-= 1;
223 $this->_autocommit
= true;
224 $ret = odbc_commit($this->_connectionID
);
225 odbc_autocommit($this->_connectionID
,true);
229 function RollbackTrans()
231 if ($this->transOff
) return true;
232 if ($this->transCnt
) $this->transCnt
-= 1;
233 $this->_autocommit
= true;
234 $ret = odbc_rollback($this->_connectionID
);
235 odbc_autocommit($this->_connectionID
,true);
239 function MetaPrimaryKeys($table)
241 global $ADODB_FETCH_MODE;
243 if ($this->uCaseTables
) $table = strtoupper($table);
245 $this->_findschema($table,$schema);
247 $savem = $ADODB_FETCH_MODE;
248 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
249 $qid = @odbc_primarykeys
($this->_connectionID
,'',$schema,$table);
252 $ADODB_FETCH_MODE = $savem;
255 $rs = new ADORecordSet_odbc($qid);
256 $ADODB_FETCH_MODE = $savem;
258 if (!$rs) return false;
259 $rs->_has_stupid_odbc_fetch_api_change
= $this->_has_stupid_odbc_fetch_api_change
;
261 $arr = $rs->GetArray();
265 for ($i=0; $i < sizeof($arr); $i++
) {
266 if ($arr[$i][3]) $arr2[] = $arr[$i][3];
273 function MetaTables($ttype=false)
275 global $ADODB_FETCH_MODE;
277 $savem = $ADODB_FETCH_MODE;
278 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
279 $qid = odbc_tables($this->_connectionID
);
281 $rs = new ADORecordSet_odbc($qid);
283 $ADODB_FETCH_MODE = $savem;
288 $rs->_has_stupid_odbc_fetch_api_change
= $this->_has_stupid_odbc_fetch_api_change
;
290 $arr = $rs->GetArray();
297 $isview = strncmp($ttype,'V',1) === 0;
299 for ($i=0; $i < sizeof($arr); $i++
) {
300 if (!$arr[$i][2]) continue;
304 if (strncmp($type,'V',1) === 0) $arr2[] = $arr[$i][2];
305 } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
306 } else if (strncmp($type,'SYS',3) !== 0) $arr2[] = $arr[$i][2];
312 See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/odbcdatetime_data_type_changes.asp
313 / SQL data type codes /
314 #define SQL_UNKNOWN_TYPE 0
316 #define SQL_NUMERIC 2
317 #define SQL_DECIMAL 3
318 #define SQL_INTEGER 4
319 #define SQL_SMALLINT 5
323 #if (ODBCVER >= 0x0300)
324 #define SQL_DATETIME 9
326 #define SQL_VARCHAR 12
329 / One-parameter shortcuts for date/time data types /
330 #if (ODBCVER >= 0x0300)
331 #define SQL_TYPE_DATE 91
332 #define SQL_TYPE_TIME 92
333 #define SQL_TYPE_TIMESTAMP 93
335 #define SQL_UNICODE (-95)
336 #define SQL_UNICODE_VARCHAR (-96)
337 #define SQL_UNICODE_LONGVARCHAR (-97)
339 function ODBCTypes($t)
341 switch ((integer)$t) {
369 case -11: // uniqidentifier
379 function MetaColumns($table, $normalize=true)
381 global $ADODB_FETCH_MODE;
384 if ($this->uCaseTables
) $table = strtoupper($table);
386 $this->_findschema($table,$schema);
388 $savem = $ADODB_FETCH_MODE;
389 $ADODB_FETCH_MODE = ADODB_FETCH_NUM
;
391 /*if (false) { // after testing, confirmed that the following does not work becoz of a bug
392 $qid2 = odbc_tables($this->_connectionID);
393 $rs = new ADORecordSet_odbc($qid2);
394 $ADODB_FETCH_MODE = $savem;
395 if (!$rs) return false;
396 $rs->_has_stupid_odbc_fetch_api_change = $this->_has_stupid_odbc_fetch_api_change;
400 if ($table == strtoupper($rs->fields[2])) {
409 $qid = odbc_columns($this->_connectionID,$q,$o,strtoupper($table),'%');
412 switch ($this->databaseType
) {
415 $qid = odbc_columns($this->_connectionID
);#,'%','',strtoupper($table),'%');
421 $qid = odbc_columns($this->_connectionID
, "", $schema, $table, $colname);
425 $qid = @odbc_columns
($this->_connectionID
,'%','%',strtoupper($table),'%');
426 if (empty($qid)) $qid = odbc_columns($this->_connectionID
);
429 if (empty($qid)) return $false;
431 $rs = new ADORecordSet_odbc($qid);
432 $ADODB_FETCH_MODE = $savem;
434 if (!$rs) return $false;
435 $rs->_has_stupid_odbc_fetch_api_change
= $this->_has_stupid_odbc_fetch_api_change
;
456 // adodb_pr($rs->fields);
457 if (strtoupper(trim($rs->fields
[2])) == $table && (!$schema ||
strtoupper($rs->fields
[1]) == $schema)) {
458 $fld = new ADOFieldObject();
459 $fld->name
= $rs->fields
[3];
460 $fld->type
= $this->ODBCTypes($rs->fields
[4]);
462 // ref: http://msdn.microsoft.com/library/default.asp?url=/archive/en-us/dnaraccgen/html/msdn_odk.asp
463 // access uses precision to store length for char/varchar
464 if ($fld->type
== 'C' or $fld->type
== 'X') {
465 if ($this->databaseType
== 'access')
466 $fld->max_length
= $rs->fields
[6];
467 else if ($rs->fields
[4] <= -95) // UNICODE
468 $fld->max_length
= $rs->fields
[7]/2;
470 $fld->max_length
= $rs->fields
[7];
472 $fld->max_length
= $rs->fields
[7];
473 $fld->not_null
= !empty($rs->fields
[10]);
474 $fld->scale
= $rs->fields
[8];
475 $retarr[strtoupper($fld->name
)] = $fld;
476 } else if (sizeof($retarr)>0)
480 $rs->Close(); //-- crashes 4.03pl1 -- why?
482 if (empty($retarr)) $retarr = false;
486 function Prepare($sql)
488 if (! $this->_bindInputArray
) return $sql; // no binding
489 $stmt = odbc_prepare($this->_connectionID
,$sql);
491 // we don't know whether odbc driver is parsing prepared stmts, so just return sql
494 return array($sql,$stmt,false);
497 /* returns queryID or false */
498 function _query($sql,$inputarr=false)
500 GLOBAL $php_errormsg;
501 if (isset($php_errormsg)) $php_errormsg = '';
505 if (is_array($sql)) {
508 $stmtid = odbc_prepare($this->_connectionID
,$sql);
510 if ($stmtid == false) {
511 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
516 if (! odbc_execute($stmtid,$inputarr)) {
517 //@odbc_free_result($stmtid);
518 if ($this->_haserrorfunctions
) {
519 $this->_errorMsg
= odbc_errormsg();
520 $this->_errorCode
= odbc_error();
525 } else if (is_array($sql)) {
527 if (!odbc_execute($stmtid)) {
528 //@odbc_free_result($stmtid);
529 if ($this->_haserrorfunctions
) {
530 $this->_errorMsg
= odbc_errormsg();
531 $this->_errorCode
= odbc_error();
536 $stmtid = odbc_exec($this->_connectionID
,$sql);
538 $this->_lastAffectedRows
= 0;
540 if (@odbc_num_fields
($stmtid) == 0) {
541 $this->_lastAffectedRows
= odbc_num_rows($stmtid);
544 $this->_lastAffectedRows
= 0;
545 odbc_binmode($stmtid,$this->binmode
);
546 odbc_longreadlen($stmtid,$this->maxblobsize
);
549 if ($this->_haserrorfunctions
) {
550 $this->_errorMsg
= '';
551 $this->_errorCode
= 0;
553 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
555 if ($this->_haserrorfunctions
) {
556 $this->_errorMsg
= odbc_errormsg();
557 $this->_errorCode
= odbc_error();
559 $this->_errorMsg
= isset($php_errormsg) ?
$php_errormsg : '';
565 Insert a null into the blob field of the table first.
566 Then use UpdateBlob to store the blob.
570 $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
571 $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
573 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
575 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
578 // returns true or false
581 $ret = @odbc_close
($this->_connectionID
);
582 $this->_connectionID
= false;
586 function _affectedrows()
588 return $this->_lastAffectedRows
;
593 /*--------------------------------------------------------------------------------------
594 Class Name: Recordset
595 --------------------------------------------------------------------------------------*/
597 class ADORecordSet_odbc
extends ADORecordSet
{
600 var $databaseType = "odbc";
601 var $dataProvider = "odbc";
603 var $_has_stupid_odbc_fetch_api_change;
605 function ADORecordSet_odbc($id,$mode=false)
607 if ($mode === false) {
608 global $ADODB_FETCH_MODE;
609 $mode = $ADODB_FETCH_MODE;
611 $this->fetchMode
= $mode;
613 $this->_queryID
= $id;
615 // the following is required for mysql odbc driver in 4.3.1 -- why?
617 $this->_currentRow
= -1;
618 //$this->ADORecordSet($id);
622 // returns the field object
623 function FetchField($fieldOffset = -1)
626 $off=$fieldOffset+
1; // offsets begin at 1
628 $o= new ADOFieldObject();
629 $o->name
= @odbc_field_name
($this->_queryID
,$off);
630 $o->type
= @odbc_field_type
($this->_queryID
,$off);
631 $o->max_length
= @odbc_field_len
($this->_queryID
,$off);
632 if (ADODB_ASSOC_CASE
== 0) $o->name
= strtolower($o->name
);
633 else if (ADODB_ASSOC_CASE
== 1) $o->name
= strtoupper($o->name
);
637 /* Use associative array to get fields array */
638 function Fields($colname)
640 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) return $this->fields
[$colname];
642 $this->bind
= array();
643 for ($i=0; $i < $this->_numOfFields
; $i++
) {
644 $o = $this->FetchField($i);
645 $this->bind
[strtoupper($o->name
)] = $i;
649 return $this->fields
[$this->bind
[strtoupper($colname)]];
655 global $ADODB_COUNTRECS;
656 $this->_numOfRows
= ($ADODB_COUNTRECS) ? @odbc_num_rows
($this->_queryID
) : -1;
657 $this->_numOfFields
= @odbc_num_fields
($this->_queryID
);
658 // some silly drivers such as db2 as/400 and intersystems cache return _numOfRows = 0
659 if ($this->_numOfRows
== 0) $this->_numOfRows
= -1;
660 //$this->useFetchArray = $this->connection->useFetchArray;
661 $this->_has_stupid_odbc_fetch_api_change
= ADODB_PHPVER
>= 0x4200;
669 // speed up SelectLimit() by switching to ADODB_FETCH_NUM as ADODB_FETCH_ASSOC is emulated
670 function GetArrayLimit($nrows,$offset=-1)
673 $rs = $this->GetArray($nrows);
676 $savem = $this->fetchMode
;
677 $this->fetchMode
= ADODB_FETCH_NUM
;
678 $this->Move($offset);
679 $this->fetchMode
= $savem;
681 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) {
682 $this->fields
= $this->GetRowAssoc(ADODB_ASSOC_CASE
);
687 while (!$this->EOF
&& $nrows != $cnt) {
688 $results[$cnt++
] = $this->fields
;
698 if ($this->_numOfRows
!= 0 && !$this->EOF
) {
699 $this->_currentRow++
;
701 if ($this->_has_stupid_odbc_fetch_api_change
)
702 $rez = @odbc_fetch_into
($this->_queryID
,$this->fields
);
705 $rez = @odbc_fetch_into
($this->_queryID
,$row,$this->fields
);
708 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) {
709 $this->fields
= $this->GetRowAssoc(ADODB_ASSOC_CASE
);
714 $this->fields
= false;
722 if ($this->_has_stupid_odbc_fetch_api_change
)
723 $rez = @odbc_fetch_into
($this->_queryID
,$this->fields
);
726 $rez = @odbc_fetch_into
($this->_queryID
,$row,$this->fields
);
729 if ($this->fetchMode
& ADODB_FETCH_ASSOC
) {
730 $this->fields
= $this->GetRowAssoc(ADODB_ASSOC_CASE
);
734 $this->fields
= false;
740 return @odbc_free_result
($this->_queryID
);