PHP, WEB

Simple MSSQL Connection Class

A simple mssql(Microsoft SQL Server) connection class!

All the code below is licensed under GPLv3!

Main mssql class file – mssql.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
    SMSSC - Simple MSSQL Connection
    Copyright (C) 2012  KARPOUZAS GEORGE
 
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
 
class mssqldb{
    private $_connection;
    private $_dbselect;
    private $_result;
 
    public function  __construct()
    {
        require_once('db.inc.php');
    }
 
    public function connect()
    {
        $this->_connection = @mssql_connect(DB_HOST, DB_USER, DB_PASS);
        if(!$this->_connection)
        {
            die('<font color="red">Error: Unable to connect to database host.</font>');
        }
        $this->_dbselect = @mssql_select_db(DB_NAME, $this->_connection);
        if(!$this->_dbselect)
        {
            die('<font color="red">Error: Unable to select database.</font>');
        }
    }
 
    public function query($sql)
    {
        $this->_result = @mssql_query($sql);
        if(!$this->_result)
        {
            die('<font color="red">Error: Could not run query.</font>');
        }
        return $this->_result;
    }
 
    public function free()
    {
        mssql_free_result($this->_result);
    }
 
    public function disconnect()
    {
        mssql_close($this->_connection);
    }
}

 

Database credentials file – db.inc.php

1
2
3
4
defined ( 'DB_HOST' ) ? null : define ( 'DB_HOST', 'localhost' );
defined ( 'DB_USER' ) ? null : define ( 'DB_USER', 'dbuser' );
defined ( 'DB_PASS' ) ? null : define ( 'DB_PASS', 'dbpass' );
defined ( 'DB_NAME' ) ? null : define ( 'DB_NAME', 'dbname' );

 

Testing file – index.php

1
2
3
4
5
6
7
8
9
require_once('mssql.php');
$mysqlconn = new mssqldb();
echo 'Connecting to server..<br>';
$mysqlconn->connect();
echo 'Executing a query..<br>';
$mysqlconn->query('select * from customer;');
echo 'Disconnecting from server..<br>';
$mysqlconn->free();
$mysqlconn->disconnect();