2016-08-29 52 views
1

在我的數據庫類中,我有一個方法query(),它將SQL語句和參數作爲參數並在數據庫中運行它們。BindParam()無法正常工作

// the parameters are the sql statement and the values, returns the the current object 
    // the result set object can be accessed by using the results() method 

    public function query($sql, $params = array()) { 

     $this->_error = false; // initially the error is set to false 

     if($this->_query = $this->_pdo->prepare($sql)) { 

      // if the parameters are set, bind it with the statement 
      if(count($params)) { 
       foreach($params as $param => $value) { 
        $this->_query->bindParam($param, $value); 
       } 
      } 

      // if the query is successfully executed save the resultset object to the $_results property 
      // and store the total row count in $_count 
      if($this->_query->execute()) { 
       $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ); 
       $this->_count = $this->_query->rowCount(); 
      } else { 
       $this->_error = true; 
      } 
     } 

     return $this; 

    } 

,這是怎麼了調用該方法

$db->query("SELECT * FROM users WHERE username = :username AND id = :id ", array(':username' => 'sayantan94', ':id' => 1)); 

但是,當我print_r()結果集,我得到一個空數組。但是,如果我這樣做

$db->query("SELECT * FROM users WHERE username = :username", array(':username' => 'sayantan94')); 

或本

$db->query("SELECT * FROM users WHERE id = :id ", array(':id' => 1)); 

我得到正確的結果。我的代碼有什麼問題?

回答

2

除了什麼是對方回答說,大部分代碼是無用的或有害的。事實上,你只需要這幾行

public function query($sql, $params = array()) 
{ 
    $query = $this->_pdo->prepare($sql); 
    $query->execute($params); 
    return $query; 
} 

它會盡你所能的功能,但沒有那麼多的代碼和沒有討厭的副作用。想象一下你會在循環中運行一個嵌套的查詢。第二次查詢執行後,你的$ this - > _ results變量會變成什麼?在這樣的函數中,不應該有與特定查詢相關的類變量。

此外,

  • 無需手動檢查準備的結果 - PDO將被自己拋出異常
  • 沒有必要爲_error變量,因爲它是好看不中用,而PDO自身的異常是方式更有用和信息性更強
  • 無需綁定循環 -​​可以一次綁定所有參數
  • 無需測試$params數組 -​​也將接受一個空數組。
  • 無需返回fetchAll() restult - 你總是可以做到這一點後,通過鏈接像這樣$data = $db->query($sql, $params)->fetchAll();
  • 沒有必要rowCount() - 你總是可以只統計數組從使用fetchall()
+0

This工作。謝謝你的建議。我現在在學習。 –

+0

@SayantanDas請查閱我的文章,以深入解釋您正在使用的一些不良做法,[您的第一個數據庫包裝的兒童疾病](https://phpdelusions.net/pdo/common_mistakes) –

+0

謝謝。我一定會檢查那篇文章。 –

1

您的foreach是假的,通過價值$價值,因爲bindParam需要& $變量,做一個參考,試試這個:

if(count($params)) { 
    foreach($params as $param => &$value) { 
     $this->_query->bindParam($param, $value); 
    } 
} 

http://php.net/manual/en/pdostatement.bindparam.php

+0

我回到獲取此錯誤警告:PDOStatement :: bindParam():SQLSTATE [HY093]:無效的參數編號:列/參數是基於1的D:\ xampp \ htdocs \ oop \ classes \ DB.php在第50行上 –