2014-11-24 64 views
-1

我想提取取決於多個條件從MySQL數據庫的數據,但我的行爲函數中使用數組中的面向對象的編程讓我來提取僅基於1個條件數據。難度在PHP

請幫我修改操作函數,這樣我可以使用多個陣列來提取數據。

public function query($sql, $params = array()) { 
    $this->error = false; 
    if ($this->query = $this->pdo->prepare($sql)) { 
     $x = 1; 
     if (count($params)) { 
      foreach ($params as $param) { 
       $this->query->bindValue($x, $param); 
       $x++; 
      } 
     } 
     if ($this->query->execute()) { 
      $this->results = $this->query->fetchAll(PDO::FETCH_OBJ); 
      $this->count = $this->query->rowCount(); 
     } else { 
      $this->error = true; 
     } 
    } 
    return $this; 
} 

public function action($action, $table, $where = array()) { 
    if (count($where === 3)) { 
     $operators = array('=', '>', '<', '>=', '<='); 

     $field = $where[0]; 
     $operator = $where[1]; 
     $value = $where[2]; 

     if (in_array($operator, $operators)) { 
      $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; 

      if (!$this->query($sql, array($value))->error()) { 
       return $this; 
      } 
     } 
    } 
    return false; 
} 

public function get($table, $where) { 
    return $this->action('SELECT *', $table, $where); 
} 
+0

這是對最壞的可能設計一個數據庫抽象層,你可以拿出。 'action'?祝你好運,當你嘗試使用'更新'。 – 2014-11-24 17:31:10

回答

1

在對象的定向器ORM層是常見的有一個單獨的類聲明,或者更具體地,爲SELECT語句,例如

$users = $db->select('*') 
    ->from('users') 
    ->where('id', '>', 100) 
    ->where('name', 'like', 'agg%') 
    ->orderBy('name') 
    ->execute() 
    ->getResults(); 

這將是一個偉大的學習練習設計一個類,允許類似的東西。

+0

我是新來的OOP,可以請你幫我解釋一下你答,這樣我可以很容易地理解它 – aggarwal 2014-11-24 17:43:03

+0

@aggarwal:這就是所謂的[「流利接口」(http://en.wikipedia.org/wiki/Fluent_interface# PHP)。基本上,你創建一個對象並使用方法來設置它的屬性。每個這樣的方法返回'$ this',從而允許進一步的鏈接。 – georg 2014-11-24 17:45:46