mysql.php (2258B)
1 <?php 2 namespace DB; 3 final class MySQL { 4 private $connection; 5 6 public function __construct($hostname, $username, $password, $database, $port = '3306') { 7 if (!$this->connection = mysql_connect($hostname . ':' . $port, $username, $password)) { 8 trigger_error('Error: Could not make a database link using ' . $username . '@' . $hostname); 9 exit(); 10 } 11 12 if (!mysql_select_db($database, $this->connection)) { 13 throw new \Exception('Error: Could not connect to database ' . $database); 14 } 15 16 mysql_query("SET NAMES 'utf8'", $this->connection); 17 mysql_query("SET CHARACTER SET utf8", $this->connection); 18 mysql_query("SET CHARACTER_SET_CONNECTION=utf8", $this->connection); 19 mysql_query("SET SQL_MODE = ''", $this->connection); 20 } 21 22 public function query($sql) { 23 if ($this->connection) { 24 $resource = mysql_query($sql, $this->connection); 25 26 if ($resource) { 27 if (is_resource($resource)) { 28 $i = 0; 29 30 $data = array(); 31 32 while ($result = mysql_fetch_assoc($resource)) { 33 $data[$i] = $result; 34 35 $i++; 36 } 37 38 mysql_free_result($resource); 39 40 $query = new \stdClass(); 41 $query->row = isset($data[0]) ? $data[0] : array(); 42 $query->rows = $data; 43 $query->num_rows = $i; 44 45 unset($data); 46 47 return $query; 48 } else { 49 return true; 50 } 51 } else { 52 $trace = debug_backtrace(); 53 54 throw new \Exception('Error: ' . mysql_error($this->connection) . '<br />Error No: ' . mysql_errno($this->connection) . '<br /> Error in: <b>' . $trace[1]['file'] . '</b> line <b>' . $trace[1]['line'] . '</b><br />' . $sql); 55 } 56 } 57 } 58 59 public function escape($value) { 60 if ($this->connection) { 61 return mysql_real_escape_string($value, $this->connection); 62 } 63 } 64 65 public function countAffected() { 66 if ($this->connection) { 67 return mysql_affected_rows($this->connection); 68 } 69 } 70 71 public function getLastId() { 72 if ($this->connection) { 73 return mysql_insert_id($this->connection); 74 } 75 } 76 77 public function isConnected() { 78 if ($this->connection) { 79 return true; 80 } else { 81 return false; 82 } 83 } 84 85 public function __destruct() { 86 if ($this->connection) { 87 mysql_close($this->connection); 88 } 89 } 90 }