-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.php
105 lines (89 loc) · 3.37 KB
/
connection.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
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
require_once 'settings.php';
/*****************************************************
** **
** Class database written by Steven A. Gabarró **
** Modified by Phil Barresi **
** **
****************************************************/
class DatabaseConnection
{
private $host = "localhost";
private $username = "username";
private $password = "password";
private $database = "";
private $mysqli;
// This is your constructor
public function __construct ()
{
global $db_connection;
$host = $db_connection['host'];
$username = $db_connection['username'];
$password = $db_connection['password'];
$database = $db_connection['database'];
$this->setup($host, $username, $password, $database);
}
// When the object is destroyed, disconnect from the database to free up sources
public function __destruct ()
{
$this->disconnect();
}
// If you had multiple databases or are using a non default database, you would need to change the database
public function change_database ($newDb)
{
$this->database = $newDb;
if (isset($this->mysqli))
$this->mysqli->select_db($newDb);
else
$this->connect();
}
// sets user, pass and host and connects
public function setup ($host, $username, $password, $db)
{
$this->host = $host;
$this->username = $username;
$this->password = $password;
$this->database = $db;
if (isset($this->mysqli))
$this->disconnect();
$this->connect();
}
//Closes the connection to the DB
public function disconnect ()
{
if (isset($this->mysqli))
$this->mysqli->close();
if (isset($this->res) && gettype($this->res) == "object") {
$this->res->free();
}
unset($this->res);
unset($this->mysqli);
}
// connects to the DB or disconnects/reconnects if a connection already existed
public function connect ()
{
if (isset($this->mysqli))
$this->disconnect();
try {
if (!$this->mysqli = new mysqli($this->host, $this->username, $this->password, $this->database))
throw new Exception("Cannot Connect to " . $this->host);
} catch (Exception $e) {
echo $e->getMessage();
exit;
}
}
public function prepare_statement($statement) {
if (!isset($this->mysqli)) $this->connect();
return $this->mysqli->prepare($statement);
}
public function send_sql($statement) {
if (!isset($this->mysqli)) $this->connect();
$statement = $this->mysqli->real_escape_string($statement);
return $this->mysqli->query($statement);
}
public function send_sql_email($statement) {
if (!isset($this->mysqli)) $this->connect();
return $this->mysqli->query($statement);
}
}
?>