/sql/mssql
[return to app]1
<?php
2 /**
3 * Converts the procedural MS SQL class to object-oriented
4 */
5 class mssql {
6 /**
7 * Database resource ID
8 * @var object
9 */
10 public $resource;
11
12 /**
13 * The database method used to sanitize user input strings
14 */
15 const ESCAPE_STRING = 'escapeString';
16
17 /**
18 * Creates a string sanitation method as it is missing in the MS SQL PHP extension
19 *
20 * @param string $var
21 * @return string
22 */
23 public function escapeString($var) {
24 return str_replace("'", "''", $var);
25 }
26
27 /**
28 * Alias for db2_exec() to update DB2 extension to use the modern naming convention
29 * and not require passing the connection to every statement via argument
30 *
31 * @param string $query
32 * @param array $options Optional
33 * @return resource
34 */
35 public function query($query, $options = null) {
36 return db2_exec($this->resource, $query, $options);
37 }
38
39 /**
40 * Connect to MS SQL
41 *
42 * @param string $host
43 * @param string $username
44 * @param string $passwd
45 * @param string $dbname Optional
46 * @param boolean $persistent Optional default is true
47 * @param boolean $newLink Optional default is null (equates to false)
48 */
49 public function __construct($host, $username, $password, $dbname = null, $persistent = true, $newLink = null)
{
50 try {
51 $connect = 'mssql_' . ($persistent ? 'pconnect' : 'connect');
52 $this->resource = $connect($host, $username, $password, $dbname, $newLink);
53 if (!$this->resource) {
54 throw new Exception('Cannot connect to MS SQL');
55 }
56 } catch (Exception $e) {
57 $this->error = $e->getMessage();
58 }
59 if ($dbname) {
60 mssql_select_db($dbname, $this->resource);
61 }
62 }
63
64 /**
65 * Catch-all method allowing you to call any MS SQL function via camel-cap object-oriented syntax.
66 *
67 * From your models you could access:
68 *
69 * $this->db->fetchBatch()
70 * $this->db->fetchAssoc()
71 * $this->db->query()
72 * $this->db->freeStatement()
73 * $this->db->rowsAffected()
74 * $this->db->close()
75 * etc.
76 *
77 * @param string $name
78 * @param mixed $val
79 */
80 public function __call($name, $val) {
81 $name = strtolower('mssql_' . preg_replace('/[A-Z]/', '_$0', $name));
82 if (function_exists($name)) {
83 return call_user_func_array($name, $val);
84 }
85 }
86 }