PHP, WEB

Simple MySQL Connection Class

A simple mysql connection class to make your life a little bit easier!

All the code below is licensed under GPLv3!

Main mysql class file (mysql_class.php – mysql_class)

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
class mysqldb{
    private $_connection;
    private $_dbselect;
    private $_result;
 
    public function  __construct()
    {
        require_once('db.inc.php');
    }
 
    public function connect()
    {
        $this->_connection = @mysql_connect(DB_HOST, DB_USER, DB_PASS);
        if(!$this->_connection)
        {
            die('<font color="red">Error: Unable to connect to database host ('.mysql_error().')</font>');
        }
        $this->_dbselect = @mysql_select_db(DB_NAME, $this->_connection);
        if(!$this->_dbselect)
        {
            die('<font color="red">Error: Unable to select database ('.mysql_error().')</font>');
        }
    }
 
    public function query($sql)
    {
        $this->_result = @mysql_query($sql);
        if(!$this->_result)
        {
            die('<font color="red">Error: Could not run query ('.mysql_error().')</font>');
        }
        return $this->_result;
    }
 
    public function free()
    {
        mysql_free_result($this->_result);
    }
 
    public function disconnect()
    {
        mysql_close($this->_connection);
    }
}

 

Database credentials file (db.inc.php – db.inc)

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' );

 

Index – Testing file (index.php – index)

1
2
3
4
5
6
require_once('mysql_class.php');
$mysqlconn = new mysqldb();
$mysqlconn->connect();
$mysqlconn->query('select * from persons;');
$mysqlconn->free();
$mysqlconn->disconnect();