<?php 
 
class DAL {

  private $link = NULL;
 
  public function __construct(){}
   
  public function query($sql) {

    $op = strtoupper(substr($sql, 0, strpos ($sql, " ")));

    if ($op == "SELECT") {
      if (strpos ($sql, "LIMIT 1") == 0)
        return $this->select($sql);
      else
        return $this->selOne($sql);
    }
    else if ($op == "CALL") {
      return $this->select($sql);
    }
    else
      return $this->modify($sql);
  }
    
  private function dbconnect() {

    $conn = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    $this->conn = $conn;

    return true;
  }
   
  private function selOne ($sql) {

    $this->dbconnect();

    $rows = $this->conn->query($sql);
  
    if (!$rows) {
      die ($this->conn->error . " - " . $sql);  
    }
    
    // Declare an empty array	
    $result = array(); // using [] instead of array() also works
    
    if ($rows->num_rows == 1)
      $result = $rows->fetch_object();

    $this->conn->close();

    return $result;
  }

  private function select ($sql) {

    $this->dbconnect();

    $rows = $this->conn->query($sql);
  
    if (!$rows) {
      die ($this->conn->error . " - " . $sql);  
    }
    
    // Declare an empty array	
    $result = array(); // using [] instead of array() also works
    
    while ($row = $rows->fetch_object()) {
      $result[] = $row;
    }      

    $this->conn->close();

    return $result;
  }

  private function modify ($sql) {

    $this->dbconnect();

    if ($this->conn->query($sql) === TRUE)
      $result = TRUE;
    else 
     die ($this->conn->error . " - " . $sql);  
 
    if ($this->conn->insert_id > 0)
	  $result = $this->conn->insert_id;
    
    $this->conn->close();

    return $result;
  }

}
?>