summaryrefslogtreecommitdiff
path: root/includes/libs/libmysql.php
blob: 5a3a06cb292749f0ef52beca89fdb255fe4522c8 (plain) (blame)
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
<?php

require_once "includes/conf/mysql.conf.php";

class Database
{
	// implement singleton pattern
	static private $instance = null;
	
	private $conn;

	static public function getInstance()
    {
		if (null === self::$instance) 
		{
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	// ctor
	private function __construct()
	{
		global $conf;
		$this->conn = mysql_connect( $conf['mysql_hostname'], 
			$conf['mysql_username'], 
			$conf['mysql_password'] ) 
			or die ("Connection to database failed!" . mysql_error());
			
		mysql_select_db( $conf['mysql_database'], $this->conn )
			or die ("Selection of database failed! " . mysql_error());
	}
	
	private function checkConnect()
	{
		if (!isset($this->conn))
		{
			die("Not connected to database");
		}
	}
	
	// returns the value in the first row and column
	public function getValue( $sql )
	{
		$this->checkConnect();
		
		$res = mysql_query( $sql, $this->conn );
		if (!$res) 
		{
			die('Error while calling database: ' . mysql_error());
		}
		$vals = mysql_fetch_row( $res );
		mysql_free_result( $res );
		return $vals[0];
	}
	
	// executes some sql and returns affected rows
	public function exec( $sql )
	{
		$this->checkConnect();
		
		$res = mysql_query( $sql, $this->conn );
		if (!$res) 
		{
			die('Error while calling database: ' . mysql_error());
		}
		$numrows = mysql_affected_rows( $this->conn );
		return $numrows;
	}
	
	public function escape( $string )
	{
		$this->checkConnect();
		
		return mysql_real_escape_string( $string, $this->conn );
	}
	
	public function disconnect()
	{
		if ( mysql_ping( $this->conn ) )
		{
			mysql_close( $this->conn );
		}
	}
	
}


?>