adodb-mssql.inc.php 29 KB

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