PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/MantisBT/library/adodb/drivers/adodb-mssql.inc.php

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