PageRenderTime 64ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/libraries/adodb.493a/drivers/adodb-mssql.inc.php

https://github.com/guzzisto/retrospect-gds
PHP | 1037 lines | 853 code | 85 blank | 99 comment | 96 complexity | e4959656be6dcf08972715f61213b714 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1
  1. <?php
  2. /*
  3. V4.93 10 Oct 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). 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.
  8. Latest version is available at http://adodb.sourceforge.net
  9. Native mssql driver. Requires mssql client. Works on Windows.
  10. To configure for Unix, see
  11. http://phpbuilder.com/columns/alberto20000919.php3
  12. */
  13. // security - hide paths
  14. if (!defined('ADODB_DIR')) die();
  15. //----------------------------------------------------------------
  16. // MSSQL returns dates with the format Oct 13 2002 or 13 Oct 2002
  17. // and this causes tons of problems because localized versions of
  18. // MSSQL will return the dates in dmy or mdy order; and also the
  19. // month strings depends on what language has been configured. The
  20. // following two variables allow you to control the localization
  21. // settings - Ugh.
  22. //
  23. // MORE LOCALIZATION INFO
  24. // ----------------------
  25. // To configure datetime, look for and modify sqlcommn.loc,
  26. // typically found in c:\mssql\install
  27. // Also read :
  28. // http://support.microsoft.com/default.aspx?scid=kb;EN-US;q220918
  29. // Alternatively use:
  30. // CONVERT(char(12),datecol,120)
  31. //----------------------------------------------------------------
  32. // has datetime converstion to YYYY-MM-DD format, and also mssql_fetch_assoc
  33. if (ADODB_PHPVER >= 0x4300) {
  34. // docs say 4.2.0, but testing shows only since 4.3.0 does it work!
  35. ini_set('mssql.datetimeconvert',0);
  36. } else {
  37. global $ADODB_mssql_mths; // array, months must be upper-case
  38. $ADODB_mssql_date_order = 'mdy';
  39. $ADODB_mssql_mths = array(
  40. 'JAN'=>1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,
  41. 'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12);
  42. }
  43. //---------------------------------------------------------------------------
  44. // Call this to autoset $ADODB_mssql_date_order at the beginning of your code,
  45. // just after you connect to the database. Supports mdy and dmy only.
  46. // Not required for PHP 4.2.0 and above.
  47. function AutoDetect_MSSQL_Date_Order($conn)
  48. {
  49. global $ADODB_mssql_date_order;
  50. $adate = $conn->GetOne('select getdate()');
  51. if ($adate) {
  52. $anum = (int) $adate;
  53. if ($anum > 0) {
  54. if ($anum > 31) {
  55. //ADOConnection::outp( "MSSQL: YYYY-MM-DD date format not supported currently");
  56. } else
  57. $ADODB_mssql_date_order = 'dmy';
  58. } else
  59. $ADODB_mssql_date_order = 'mdy';
  60. }
  61. }
  62. class ADODB_mssql extends ADOConnection {
  63. var $databaseType = "mssql";
  64. var $dataProvider = "mssql";
  65. var $replaceQuote = "''"; // string to use to replace quotes
  66. var $fmtDate = "'Y-m-d'";
  67. var $fmtTimeStamp = "'Y-m-d H:i:s'";
  68. var $hasInsertID = true;
  69. var $substr = "substring";
  70. var $length = 'len';
  71. var $hasAffectedRows = true;
  72. var $metaDatabasesSQL = "select name from sysdatabases where name <> 'master'";
  73. var $metaTablesSQL="select name,case when type='U' then 'T' else 'V' end 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','dtproperties'))";
  74. var $metaColumnsSQL = # xtype==61 is datetime
  75. "select c.name,t.name,c.length,
  76. (case when c.xusertype=61 then 0 else c.xprec end),
  77. (case when c.xusertype=61 then 0 else c.xscale end)
  78. from syscolumns c join systypes t on t.xusertype=c.xusertype join sysobjects o on o.id=c.id where o.name='%s'";
  79. var $hasTop = 'top'; // support mssql SELECT TOP 10 * FROM TABLE
  80. var $hasGenID = true;
  81. var $sysDate = 'convert(datetime,convert(char,GetDate(),102),102)';
  82. var $sysTimeStamp = 'GetDate()';
  83. var $_has_mssql_init;
  84. var $maxParameterLen = 4000;
  85. var $arrayClass = 'ADORecordSet_array_mssql';
  86. var $uniqueSort = true;
  87. var $leftOuter = '*=';
  88. var $rightOuter = '=*';
  89. var $ansiOuter = true; // for mssql7 or later
  90. var $poorAffectedRows = true;
  91. var $identitySQL = 'select @@IDENTITY'; // 'select SCOPE_IDENTITY'; # for mssql 2000
  92. var $uniqueOrderBy = true;
  93. var $_bindInputArray = true;
  94. function ADODB_mssql()
  95. {
  96. $this->_has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0);
  97. }
  98. function ServerInfo()
  99. {
  100. global $ADODB_FETCH_MODE;
  101. if ($this->fetchMode === false) {
  102. $savem = $ADODB_FETCH_MODE;
  103. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  104. } else
  105. $savem = $this->SetFetchMode(ADODB_FETCH_NUM);
  106. if (0) {
  107. $stmt = $this->PrepareSP('sp_server_info');
  108. $val = 2;
  109. $this->Parameter($stmt,$val,'attribute_id');
  110. $row = $this->GetRow($stmt);
  111. }
  112. $row = $this->GetRow("execute sp_server_info 2");
  113. if ($this->fetchMode === false) {
  114. $ADODB_FETCH_MODE = $savem;
  115. } else
  116. $this->SetFetchMode($savem);
  117. $arr['description'] = $row[2];
  118. $arr['version'] = ADOConnection::_findvers($arr['description']);
  119. return $arr;
  120. }
  121. function IfNull( $field, $ifNull )
  122. {
  123. return " ISNULL($field, $ifNull) "; // if MS SQL Server
  124. }
  125. function _insertid()
  126. {
  127. // SCOPE_IDENTITY()
  128. // Returns the last IDENTITY value inserted into an IDENTITY column in
  129. // the same scope. A scope is a module -- a stored procedure, trigger,
  130. // function, or batch. Thus, two statements are in the same scope if
  131. // they are in the same stored procedure, function, or batch.
  132. return $this->GetOne($this->identitySQL);
  133. }
  134. function _affectedrows()
  135. {
  136. return $this->GetOne('select @@rowcount');
  137. }
  138. var $_dropSeqSQL = "drop table %s";
  139. function CreateSequence($seq='adodbseq',$start=1)
  140. {
  141. $this->Execute('BEGIN TRANSACTION adodbseq');
  142. $start -= 1;
  143. $this->Execute("create table $seq (id float(53))");
  144. $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
  145. if (!$ok) {
  146. $this->Execute('ROLLBACK TRANSACTION adodbseq');
  147. return false;
  148. }
  149. $this->Execute('COMMIT TRANSACTION adodbseq');
  150. return true;
  151. }
  152. function GenID($seq='adodbseq',$start=1)
  153. {
  154. //$this->debug=1;
  155. $this->Execute('BEGIN TRANSACTION adodbseq');
  156. $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1");
  157. if (!$ok) {
  158. $this->Execute("create table $seq (id float(53))");
  159. $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)");
  160. if (!$ok) {
  161. $this->Execute('ROLLBACK TRANSACTION adodbseq');
  162. return false;
  163. }
  164. $this->Execute('COMMIT TRANSACTION adodbseq');
  165. return $start;
  166. }
  167. $num = $this->GetOne("select id from $seq");
  168. $this->Execute('COMMIT TRANSACTION adodbseq');
  169. return $num;
  170. // in old implementation, pre 1.90, we returned GUID...
  171. //return $this->GetOne("SELECT CONVERT(varchar(255), NEWID()) AS 'Char'");
  172. }
  173. function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  174. {
  175. if ($nrows > 0 && $offset <= 0) {
  176. $sql = preg_replace(
  177. '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop." $nrows ",$sql);
  178. $rs =& $this->Execute($sql,$inputarr);
  179. } else
  180. $rs =& ADOConnection::SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  181. return $rs;
  182. }
  183. // Format date column in sql string given an input format that understands Y M D
  184. function SQLDate($fmt, $col=false)
  185. {
  186. if (!$col) $col = $this->sysTimeStamp;
  187. $s = '';
  188. $len = strlen($fmt);
  189. for ($i=0; $i < $len; $i++) {
  190. if ($s) $s .= '+';
  191. $ch = $fmt[$i];
  192. switch($ch) {
  193. case 'Y':
  194. case 'y':
  195. $s .= "datename(yyyy,$col)";
  196. break;
  197. case 'M':
  198. $s .= "convert(char(3),$col,0)";
  199. break;
  200. case 'm':
  201. $s .= "replace(str(month($col),2),' ','0')";
  202. break;
  203. case 'Q':
  204. case 'q':
  205. $s .= "datename(quarter,$col)";
  206. break;
  207. case 'D':
  208. case 'd':
  209. $s .= "replace(str(day($col),2),' ','0')";
  210. break;
  211. case 'h':
  212. $s .= "substring(convert(char(14),$col,0),13,2)";
  213. break;
  214. case 'H':
  215. $s .= "replace(str(datepart(hh,$col),2),' ','0')";
  216. break;
  217. case 'i':
  218. $s .= "replace(str(datepart(mi,$col),2),' ','0')";
  219. break;
  220. case 's':
  221. $s .= "replace(str(datepart(ss,$col),2),' ','0')";
  222. break;
  223. case 'a':
  224. case 'A':
  225. $s .= "substring(convert(char(19),$col,0),18,2)";
  226. break;
  227. default:
  228. if ($ch == '\\') {
  229. $i++;
  230. $ch = substr($fmt,$i,1);
  231. }
  232. $s .= $this->qstr($ch);
  233. break;
  234. }
  235. }
  236. return $s;
  237. }
  238. function BeginTrans()
  239. {
  240. if ($this->transOff) return true;
  241. $this->transCnt += 1;
  242. $this->Execute('BEGIN TRAN');
  243. return true;
  244. }
  245. function CommitTrans($ok=true)
  246. {
  247. if ($this->transOff) return true;
  248. if (!$ok) return $this->RollbackTrans();
  249. if ($this->transCnt) $this->transCnt -= 1;
  250. $this->Execute('COMMIT TRAN');
  251. return true;
  252. }
  253. function RollbackTrans()
  254. {
  255. if ($this->transOff) return true;
  256. if ($this->transCnt) $this->transCnt -= 1;
  257. $this->Execute('ROLLBACK TRAN');
  258. return true;
  259. }
  260. function SetTransactionMode( $transaction_mode )
  261. {
  262. $this->_transmode = $transaction_mode;
  263. if (empty($transaction_mode)) {
  264. $this->Execute('SET TRANSACTION ISOLATION LEVEL READ COMMITTED');
  265. return;
  266. }
  267. if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode;
  268. $this->Execute("SET TRANSACTION ".$transaction_mode);
  269. }
  270. /*
  271. Usage:
  272. $this->BeginTrans();
  273. $this->RowLock('table1,table2','table1.id=33 and table2.id=table1.id'); # lock row 33 for both tables
  274. # some operation on both tables table1 and table2
  275. $this->CommitTrans();
  276. See http://www.swynk.com/friends/achigrik/SQL70Locks.asp
  277. */
  278. function RowLock($tables,$where,$flds='top 1 null as ignore')
  279. {
  280. if (!$this->transCnt) $this->BeginTrans();
  281. return $this->GetOne("select $flds from $tables with (ROWLOCK,HOLDLOCK) where $where");
  282. }
  283. function &MetaIndexes($table,$primary=false)
  284. {
  285. $table = $this->qstr($table);
  286. $sql = "SELECT i.name AS ind_name, C.name AS col_name, USER_NAME(O.uid) AS Owner, c.colid, k.Keyno,
  287. CASE WHEN I.indid BETWEEN 1 AND 254 AND (I.status & 2048 = 2048 OR I.Status = 16402 AND O.XType = 'V') THEN 1 ELSE 0 END AS IsPK,
  288. CASE WHEN I.status & 2 = 2 THEN 1 ELSE 0 END AS IsUnique
  289. FROM dbo.sysobjects o INNER JOIN dbo.sysindexes I ON o.id = i.id
  290. INNER JOIN dbo.sysindexkeys K ON I.id = K.id AND I.Indid = K.Indid
  291. INNER JOIN dbo.syscolumns c ON K.id = C.id AND K.colid = C.Colid
  292. WHERE LEFT(i.name, 8) <> '_WA_Sys_' AND o.status >= 0 AND O.Name LIKE $table
  293. ORDER BY O.name, I.Name, K.keyno";
  294. global $ADODB_FETCH_MODE;
  295. $save = $ADODB_FETCH_MODE;
  296. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  297. if ($this->fetchMode !== FALSE) {
  298. $savem = $this->SetFetchMode(FALSE);
  299. }
  300. $rs = $this->Execute($sql);
  301. if (isset($savem)) {
  302. $this->SetFetchMode($savem);
  303. }
  304. $ADODB_FETCH_MODE = $save;
  305. if (!is_object($rs)) {
  306. return FALSE;
  307. }
  308. $indexes = array();
  309. while ($row = $rs->FetchRow()) {
  310. if (!$primary && $row[5]) continue;
  311. $indexes[$row[0]]['unique'] = $row[6];
  312. $indexes[$row[0]]['columns'][] = $row[1];
  313. }
  314. return $indexes;
  315. }
  316. function MetaForeignKeys($table, $owner=false, $upper=false)
  317. {
  318. global $ADODB_FETCH_MODE;
  319. $save = $ADODB_FETCH_MODE;
  320. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  321. $table = $this->qstr(strtoupper($table));
  322. $sql =
  323. "select object_name(constid) as constraint_name,
  324. col_name(fkeyid, fkey) as column_name,
  325. object_name(rkeyid) as referenced_table_name,
  326. col_name(rkeyid, rkey) as referenced_column_name
  327. from sysforeignkeys
  328. where upper(object_name(fkeyid)) = $table
  329. order by constraint_name, referenced_table_name, keyno";
  330. $constraints =& $this->GetArray($sql);
  331. $ADODB_FETCH_MODE = $save;
  332. $arr = false;
  333. foreach($constraints as $constr) {
  334. //print_r($constr);
  335. $arr[$constr[0]][$constr[2]][] = $constr[1].'='.$constr[3];
  336. }
  337. if (!$arr) return false;
  338. $arr2 = false;
  339. foreach($arr as $k => $v) {
  340. foreach($v as $a => $b) {
  341. if ($upper) $a = strtoupper($a);
  342. $arr2[$a] = $b;
  343. }
  344. }
  345. return $arr2;
  346. }
  347. //From: Fernando Moreira <FMoreira@imediata.pt>
  348. function MetaDatabases()
  349. {
  350. if(@mssql_select_db("master")) {
  351. $qry=$this->metaDatabasesSQL;
  352. if($rs=@mssql_query($qry,$this->_connectionID)){
  353. $tmpAr=$ar=array();
  354. while($tmpAr=@mssql_fetch_row($rs))
  355. $ar[]=$tmpAr[0];
  356. @mssql_select_db($this->database);
  357. if(sizeof($ar))
  358. return($ar);
  359. else
  360. return(false);
  361. } else {
  362. @mssql_select_db($this->database);
  363. return(false);
  364. }
  365. }
  366. return(false);
  367. }
  368. // "Stein-Aksel Basma" <basma@accelero.no>
  369. // tested with MSSQL 2000
  370. function &MetaPrimaryKeys($table)
  371. {
  372. global $ADODB_FETCH_MODE;
  373. $schema = '';
  374. $this->_findschema($table,$schema);
  375. if (!$schema) $schema = $this->database;
  376. if ($schema) $schema = "and k.table_catalog like '$schema%'";
  377. $sql = "select distinct k.column_name,ordinal_position from information_schema.key_column_usage k,
  378. information_schema.table_constraints tc
  379. where tc.constraint_name = k.constraint_name and tc.constraint_type =
  380. 'PRIMARY KEY' and k.table_name = '$table' $schema order by ordinal_position ";
  381. $savem = $ADODB_FETCH_MODE;
  382. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  383. $a = $this->GetCol($sql);
  384. $ADODB_FETCH_MODE = $savem;
  385. if ($a && sizeof($a)>0) return $a;
  386. $false = false;
  387. return $false;
  388. }
  389. function &MetaTables($ttype=false,$showSchema=false,$mask=false)
  390. {
  391. if ($mask) {
  392. $save = $this->metaTablesSQL;
  393. $mask = $this->qstr(($mask));
  394. $this->metaTablesSQL .= " AND name like $mask";
  395. }
  396. $ret =& ADOConnection::MetaTables($ttype,$showSchema);
  397. if ($mask) {
  398. $this->metaTablesSQL = $save;
  399. }
  400. return $ret;
  401. }
  402. function SelectDB($dbName)
  403. {
  404. $this->database = $dbName;
  405. $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
  406. if ($this->_connectionID) {
  407. return @mssql_select_db($dbName);
  408. }
  409. else return false;
  410. }
  411. function ErrorMsg()
  412. {
  413. if (empty($this->_errorMsg)){
  414. $this->_errorMsg = mssql_get_last_message();
  415. }
  416. return $this->_errorMsg;
  417. }
  418. function ErrorNo()
  419. {
  420. if ($this->_logsql && $this->_errorCode !== false) return $this->_errorCode;
  421. if (empty($this->_errorMsg)) {
  422. $this->_errorMsg = mssql_get_last_message();
  423. }
  424. $id = @mssql_query("select @@ERROR",$this->_connectionID);
  425. if (!$id) return false;
  426. $arr = mssql_fetch_array($id);
  427. @mssql_free_result($id);
  428. if (is_array($arr)) return $arr[0];
  429. else return -1;
  430. }
  431. // returns true or false
  432. function _connect($argHostname, $argUsername, $argPassword, $argDatabasename)
  433. {
  434. if (!function_exists('mssql_pconnect')) return null;
  435. $this->_connectionID = mssql_connect($argHostname,$argUsername,$argPassword);
  436. if ($this->_connectionID === false) return false;
  437. if ($argDatabasename) return $this->SelectDB($argDatabasename);
  438. return true;
  439. }
  440. // returns true or false
  441. function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
  442. {
  443. if (!function_exists('mssql_pconnect')) return null;
  444. $this->_connectionID = mssql_pconnect($argHostname,$argUsername,$argPassword);
  445. if ($this->_connectionID === false) return false;
  446. // persistent connections can forget to rollback on crash, so we do it here.
  447. if ($this->autoRollback) {
  448. $cnt = $this->GetOne('select @@TRANCOUNT');
  449. while (--$cnt >= 0) $this->Execute('ROLLBACK TRAN');
  450. }
  451. if ($argDatabasename) return $this->SelectDB($argDatabasename);
  452. return true;
  453. }
  454. function Prepare($sql)
  455. {
  456. $sqlarr = explode('?',$sql);
  457. if (sizeof($sqlarr) <= 1) return $sql;
  458. $sql2 = $sqlarr[0];
  459. for ($i = 1, $max = sizeof($sqlarr); $i < $max; $i++) {
  460. $sql2 .= '@P'.($i-1) . $sqlarr[$i];
  461. }
  462. return array($sql,$this->qstr($sql2),$max);
  463. }
  464. function PrepareSP($sql)
  465. {
  466. if (!$this->_has_mssql_init) {
  467. ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
  468. return $sql;
  469. }
  470. $stmt = mssql_init($sql,$this->_connectionID);
  471. if (!$stmt) return $sql;
  472. return array($sql,$stmt);
  473. }
  474. // returns concatenated string
  475. // MSSQL requires integers to be cast as strings
  476. // automatically cast every datatype to VARCHAR(255)
  477. // @author David Rogers (introspectshun)
  478. function Concat()
  479. {
  480. $s = "";
  481. $arr = func_get_args();
  482. // Split single record on commas, if possible
  483. if (sizeof($arr) == 1) {
  484. foreach ($arr as $arg) {
  485. $args = explode(',', $arg);
  486. }
  487. $arr = $args;
  488. }
  489. array_walk($arr, create_function('&$v', '$v = "CAST(" . $v . " AS VARCHAR(255))";'));
  490. $s = implode('+',$arr);
  491. if (sizeof($arr) > 0) return "$s";
  492. return '';
  493. }
  494. /*
  495. Usage:
  496. $stmt = $db->PrepareSP('SP_RUNSOMETHING'); -- takes 2 params, @myid and @group
  497. # note that the parameter does not have @ in front!
  498. $db->Parameter($stmt,$id,'myid');
  499. $db->Parameter($stmt,$group,'group',false,64);
  500. $db->Execute($stmt);
  501. @param $stmt Statement returned by Prepare() or PrepareSP().
  502. @param $var PHP variable to bind to. Can set to null (for isNull support).
  503. @param $name Name of stored procedure variable name to bind to.
  504. @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
  505. @param [$maxLen] Holds an maximum length of the variable.
  506. @param [$type] The data type of $var. Legal values depend on driver.
  507. See mssql_bind documentation at php.net.
  508. */
  509. function Parameter(&$stmt, &$var, $name, $isOutput=false, $maxLen=4000, $type=false)
  510. {
  511. if (!$this->_has_mssql_init) {
  512. ADOConnection::outp( "Parameter: mssql_bind only available since PHP 4.1.0");
  513. return false;
  514. }
  515. $isNull = is_null($var); // php 4.0.4 and above...
  516. if ($type === false)
  517. switch(gettype($var)) {
  518. default:
  519. case 'string': $type = SQLCHAR; break;
  520. case 'double': $type = SQLFLT8; break;
  521. case 'integer': $type = SQLINT4; break;
  522. case 'boolean': $type = SQLINT1; break; # SQLBIT not supported in 4.1.0
  523. }
  524. if ($this->debug) {
  525. $prefix = ($isOutput) ? 'Out' : 'In';
  526. $ztype = (empty($type)) ? 'false' : $type;
  527. ADOConnection::outp( "{$prefix}Parameter(\$stmt, \$php_var='$var', \$name='$name', \$maxLen=$maxLen, \$type=$ztype);");
  528. }
  529. /*
  530. See http://phplens.com/lens/lensforum/msgs.php?id=7231
  531. RETVAL is HARD CODED into php_mssql extension:
  532. The return value (a long integer value) is treated like a special OUTPUT parameter,
  533. called "RETVAL" (without the @). See the example at mssql_execute to
  534. see how it works. - type: one of this new supported PHP constants.
  535. SQLTEXT, SQLVARCHAR,SQLCHAR, SQLINT1,SQLINT2, SQLINT4, SQLBIT,SQLFLT8
  536. */
  537. if ($name !== 'RETVAL') $name = '@'.$name;
  538. return mssql_bind($stmt[1], $name, $var, $type, $isOutput, $isNull, $maxLen);
  539. }
  540. /*
  541. Unfortunately, it appears that mssql cannot handle varbinary > 255 chars
  542. So all your blobs must be of type "image".
  543. Remember to set in php.ini the following...
  544. ; Valid range 0 - 2147483647. Default = 4096.
  545. mssql.textlimit = 0 ; zero to pass through
  546. ; Valid range 0 - 2147483647. Default = 4096.
  547. mssql.textsize = 0 ; zero to pass through
  548. */
  549. function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  550. {
  551. if (strtoupper($blobtype) == 'CLOB') {
  552. $sql = "UPDATE $table SET $column='" . $val . "' WHERE $where";
  553. return $this->Execute($sql) != false;
  554. }
  555. $sql = "UPDATE $table SET $column=0x".bin2hex($val)." WHERE $where";
  556. return $this->Execute($sql) != false;
  557. }
  558. // returns query ID if successful, otherwise false
  559. function _query($sql,$inputarr)
  560. {
  561. $this->_errorMsg = false;
  562. if (is_array($inputarr)) {
  563. # bind input params with sp_executesql:
  564. # see http://www.quest-pipelines.com/newsletter-v3/0402_F.htm
  565. # works only with sql server 7 and newer
  566. if (!is_array($sql)) $sql = $this->Prepare($sql);
  567. $params = '';
  568. $decl = '';
  569. $i = 0;
  570. foreach($inputarr as $v) {
  571. if ($decl) {
  572. $decl .= ', ';
  573. $params .= ', ';
  574. }
  575. if (is_string($v)) {
  576. $len = strlen($v);
  577. if ($len == 0) $len = 1;
  578. if ($len > 4000 ) {
  579. // NVARCHAR is max 4000 chars. Let's use NTEXT
  580. $decl .= "@P$i NTEXT";
  581. } else {
  582. $decl .= "@P$i NVARCHAR($len)";
  583. }
  584. $params .= "@P$i=N". (strncmp($v,"'",1)==0? $v : $this->qstr($v));
  585. } else if (is_integer($v)) {
  586. $decl .= "@P$i INT";
  587. $params .= "@P$i=".$v;
  588. } else if (is_float($v)) {
  589. $decl .= "@P$i FLOAT";
  590. $params .= "@P$i=".$v;
  591. } else if (is_bool($v)) {
  592. $decl .= "@P$i INT"; # Used INT just in case BIT in not supported on the user's MSSQL version. It will cast appropriately.
  593. $params .= "@P$i=".(($v)?'1':'0'); # True == 1 in MSSQL BIT fields and acceptable for storing logical true in an int field
  594. } else {
  595. $decl .= "@P$i CHAR"; # Used char because a type is required even when the value is to be NULL.
  596. $params .= "@P$i=NULL";
  597. }
  598. $i += 1;
  599. }
  600. $decl = $this->qstr($decl);
  601. if ($this->debug) ADOConnection::outp("<font size=-1>sp_executesql N{$sql[1]},N$decl,$params</font>");
  602. $rez = mssql_query("sp_executesql N{$sql[1]},N$decl,$params", $this->_connectionID);
  603. } else if (is_array($sql)) {
  604. # PrepareSP()
  605. $rez = mssql_execute($sql[1]);
  606. } else {
  607. $rez = mssql_query($sql,$this->_connectionID);
  608. }
  609. return $rez;
  610. }
  611. // returns true or false
  612. function _close()
  613. {
  614. if ($this->transCnt) $this->RollbackTrans();
  615. $rez = @mssql_close($this->_connectionID);
  616. $this->_connectionID = false;
  617. return $rez;
  618. }
  619. // mssql uses a default date like Dec 30 2000 12:00AM
  620. function UnixDate($v)
  621. {
  622. return ADORecordSet_array_mssql::UnixDate($v);
  623. }
  624. function UnixTimeStamp($v)
  625. {
  626. return ADORecordSet_array_mssql::UnixTimeStamp($v);
  627. }
  628. }
  629. /*--------------------------------------------------------------------------------------
  630. Class Name: Recordset
  631. --------------------------------------------------------------------------------------*/
  632. class ADORecordset_mssql extends ADORecordSet {
  633. var $databaseType = "mssql";
  634. var $canSeek = true;
  635. var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083
  636. // _mths works only in non-localised system
  637. function ADORecordset_mssql($id,$mode=false)
  638. {
  639. // freedts check...
  640. $this->hasFetchAssoc = function_exists('mssql_fetch_assoc');
  641. if ($mode === false) {
  642. global $ADODB_FETCH_MODE;
  643. $mode = $ADODB_FETCH_MODE;
  644. }
  645. $this->fetchMode = $mode;
  646. return $this->ADORecordSet($id,$mode);
  647. }
  648. function _initrs()
  649. {
  650. GLOBAL $ADODB_COUNTRECS;
  651. $this->_numOfRows = ($ADODB_COUNTRECS)? @mssql_num_rows($this->_queryID):-1;
  652. $this->_numOfFields = @mssql_num_fields($this->_queryID);
  653. }
  654. //Contributed by "Sven Axelsson" <sven.axelsson@bokochwebb.se>
  655. // get next resultset - requires PHP 4.0.5 or later
  656. function NextRecordSet()
  657. {
  658. if (!mssql_next_result($this->_queryID)) return false;
  659. $this->_inited = false;
  660. $this->bind = false;
  661. $this->_currentRow = -1;
  662. $this->Init();
  663. return true;
  664. }
  665. /* Use associative array to get fields array */
  666. function Fields($colname)
  667. {
  668. if ($this->fetchMode != ADODB_FETCH_NUM) return $this->fields[$colname];
  669. if (!$this->bind) {
  670. $this->bind = array();
  671. for ($i=0; $i < $this->_numOfFields; $i++) {
  672. $o = $this->FetchField($i);
  673. $this->bind[strtoupper($o->name)] = $i;
  674. }
  675. }
  676. return $this->fields[$this->bind[strtoupper($colname)]];
  677. }
  678. /* Returns: an object containing field information.
  679. Get column information in the Recordset object. fetchField() can be used in order to obtain information about
  680. fields in a certain query result. If the field offset isn't specified, the next field that wasn't yet retrieved by
  681. fetchField() is retrieved. */
  682. function &FetchField($fieldOffset = -1)
  683. {
  684. if ($fieldOffset != -1) {
  685. $f = @mssql_fetch_field($this->_queryID, $fieldOffset);
  686. }
  687. else if ($fieldOffset == -1) { /* The $fieldOffset argument is not provided thus its -1 */
  688. $f = @mssql_fetch_field($this->_queryID);
  689. }
  690. $false = false;
  691. if (empty($f)) return $false;
  692. return $f;
  693. }
  694. function _seek($row)
  695. {
  696. return @mssql_data_seek($this->_queryID, $row);
  697. }
  698. // speedup
  699. function MoveNext()
  700. {
  701. if ($this->EOF) return false;
  702. $this->_currentRow++;
  703. if ($this->fetchMode & ADODB_FETCH_ASSOC) {
  704. if ($this->fetchMode & ADODB_FETCH_NUM) {
  705. //ADODB_FETCH_BOTH mode
  706. $this->fields = @mssql_fetch_array($this->_queryID);
  707. }
  708. else {
  709. if ($this->hasFetchAssoc) {// only for PHP 4.2.0 or later
  710. $this->fields = @mssql_fetch_assoc($this->_queryID);
  711. } else {
  712. $flds = @mssql_fetch_array($this->_queryID);
  713. if (is_array($flds)) {
  714. $fassoc = array();
  715. foreach($flds as $k => $v) {
  716. if (is_numeric($k)) continue;
  717. $fassoc[$k] = $v;
  718. }
  719. $this->fields = $fassoc;
  720. } else
  721. $this->fields = false;
  722. }
  723. }
  724. if (is_array($this->fields)) {
  725. if (ADODB_ASSOC_CASE == 0) {
  726. foreach($this->fields as $k=>$v) {
  727. $this->fields[strtolower($k)] = $v;
  728. }
  729. } else if (ADODB_ASSOC_CASE == 1) {
  730. foreach($this->fields as $k=>$v) {
  731. $this->fields[strtoupper($k)] = $v;
  732. }
  733. }
  734. }
  735. } else {
  736. $this->fields = @mssql_fetch_row($this->_queryID);
  737. }
  738. if ($this->fields) return true;
  739. $this->EOF = true;
  740. return false;
  741. }
  742. // INSERT UPDATE DELETE returns false even if no error occurs in 4.0.4
  743. // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot!
  744. function _fetch($ignore_fields=false)
  745. {
  746. if ($this->fetchMode & ADODB_FETCH_ASSOC) {
  747. if ($this->fetchMode & ADODB_FETCH_NUM) {
  748. //ADODB_FETCH_BOTH mode
  749. $this->fields = @mssql_fetch_array($this->_queryID);
  750. } else {
  751. if ($this->hasFetchAssoc) // only for PHP 4.2.0 or later
  752. $this->fields = @mssql_fetch_assoc($this->_queryID);
  753. else {
  754. $this->fields = @mssql_fetch_array($this->_queryID);
  755. if (@is_array($$this->fields)) {
  756. $fassoc = array();
  757. foreach($$this->fields as $k => $v) {
  758. if (is_integer($k)) continue;
  759. $fassoc[$k] = $v;
  760. }
  761. $this->fields = $fassoc;
  762. }
  763. }
  764. }
  765. if (!$this->fields) {
  766. } else if (ADODB_ASSOC_CASE == 0) {
  767. foreach($this->fields as $k=>$v) {
  768. $this->fields[strtolower($k)] = $v;
  769. }
  770. } else if (ADODB_ASSOC_CASE == 1) {
  771. foreach($this->fields as $k=>$v) {
  772. $this->fields[strtoupper($k)] = $v;
  773. }
  774. }
  775. } else {
  776. $this->fields = @mssql_fetch_row($this->_queryID);
  777. }
  778. return $this->fields;
  779. }
  780. /* close() only needs to be called if you are worried about using too much memory while your script
  781. is running. All associated result memory for the specified result identifier will automatically be freed. */
  782. function _close()
  783. {
  784. $rez = mssql_free_result($this->_queryID);
  785. $this->_queryID = false;
  786. return $rez;
  787. }
  788. // mssql uses a default date like Dec 30 2000 12:00AM
  789. function UnixDate($v)
  790. {
  791. return ADORecordSet_array_mssql::UnixDate($v);
  792. }
  793. function UnixTimeStamp($v)
  794. {
  795. return ADORecordSet_array_mssql::UnixTimeStamp($v);
  796. }
  797. }
  798. class ADORecordSet_array_mssql extends ADORecordSet_array {
  799. function ADORecordSet_array_mssql($id=-1,$mode=false)
  800. {
  801. $this->ADORecordSet_array($id,$mode);
  802. }
  803. // mssql uses a default date like Dec 30 2000 12:00AM
  804. function UnixDate($v)
  805. {
  806. if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixDate($v);
  807. global $ADODB_mssql_mths,$ADODB_mssql_date_order;
  808. //Dec 30 2000 12:00AM
  809. if ($ADODB_mssql_date_order == 'dmy') {
  810. if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
  811. return parent::UnixDate($v);
  812. }
  813. if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
  814. $theday = $rr[1];
  815. $themth = substr(strtoupper($rr[2]),0,3);
  816. } else {
  817. if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4})|" ,$v, $rr)) {
  818. return parent::UnixDate($v);
  819. }
  820. if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
  821. $theday = $rr[2];
  822. $themth = substr(strtoupper($rr[1]),0,3);
  823. }
  824. $themth = $ADODB_mssql_mths[$themth];
  825. if ($themth <= 0) return false;
  826. // h-m-s-MM-DD-YY
  827. return mktime(0,0,0,$themth,$theday,$rr[3]);
  828. }
  829. function UnixTimeStamp($v)
  830. {
  831. if (is_numeric(substr($v,0,1)) && ADODB_PHPVER >= 0x4200) return parent::UnixTimeStamp($v);
  832. global $ADODB_mssql_mths,$ADODB_mssql_date_order;
  833. //Dec 30 2000 12:00AM
  834. if ($ADODB_mssql_date_order == 'dmy') {
  835. if (!preg_match( "|^([0-9]{1,2})[-/\. ]+([A-Za-z]{3})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
  836. ,$v, $rr)) return parent::UnixTimeStamp($v);
  837. if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
  838. $theday = $rr[1];
  839. $themth = substr(strtoupper($rr[2]),0,3);
  840. } else {
  841. if (!preg_match( "|^([A-Za-z]{3})[-/\. ]+([0-9]{1,2})[-/\. ]+([0-9]{4}) +([0-9]{1,2}):([0-9]{1,2}) *([apAP]{0,1})|"
  842. ,$v, $rr)) return parent::UnixTimeStamp($v);
  843. if ($rr[3] <= TIMESTAMP_FIRST_YEAR) return 0;
  844. $theday = $rr[2];
  845. $themth = substr(strtoupper($rr[1]),0,3);
  846. }
  847. $themth = $ADODB_mssql_mths[$themth];
  848. if ($themth <= 0) return false;
  849. switch (strtoupper($rr[6])) {
  850. case 'P':
  851. if ($rr[4]<12) $rr[4] += 12;
  852. break;
  853. case 'A':
  854. if ($rr[4]==12) $rr[4] = 0;
  855. break;
  856. default:
  857. break;
  858. }
  859. // h-m-s-MM-DD-YY
  860. return mktime($rr[4],$rr[5],0,$themth,$theday,$rr[3]);
  861. }
  862. }
  863. /*
  864. Code Example 1:
  865. select object_name(constid) as constraint_name,
  866. object_name(fkeyid) as table_name,
  867. col_name(fkeyid, fkey) as column_name,
  868. object_name(rkeyid) as referenced_table_name,
  869. col_name(rkeyid, rkey) as referenced_column_name
  870. from sysforeignkeys
  871. where object_name(fkeyid) = x
  872. order by constraint_name, table_name, referenced_table_name, keyno
  873. Code Example 2:
  874. select constraint_name,
  875. column_name,
  876. ordinal_position
  877. from information_schema.key_column_usage
  878. where constraint_catalog = db_name()
  879. and table_name = x
  880. order by constraint_name, ordinal_position
  881. http://www.databasejournal.com/scripts/article.php/1440551
  882. */
  883. ?>