Database.inc 803 B

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. class Database {
  3. private $mysqli;
  4. public function __construct() {
  5. $this->mysqli = new mysqli(MYSQLI_SERVER, MYSQLI_USER, MYSQLI_PASS, MYSQLI_DB);
  6. if($this->mysqli->connect_error) {
  7. throw new DatabaseConnectionException("Unable to connect");
  8. }
  9. }
  10. public function query($sql) {
  11. $mysqliResult = $this->mysqli->query($sql);
  12. if($mysqliResult === true) {
  13. return true;
  14. }
  15. $result = array();
  16. if($mysqliResult->num_rows == 0) {
  17. return $result;
  18. }
  19. while($row = $mysqliResult->fetch_assoc()) {
  20. $result[] = $row;
  21. }
  22. $mysqliResult->close();
  23. return $result;
  24. }
  25. public function write($sql) {
  26. $this->mysqli->query($sql);
  27. return $this->mysqli->insert_id;
  28. }
  29. }
  30. class DatabaseConnectionException extends Exception {}
  31. class DatabaseResultException extends Exception {}