2016-12-15 114 views
-1

我正在嘗試使用準備好的語句來使用作爲參數傳遞給類的對象屬性來設置佔位符值__construct功能。然而,我縫隙得到一個錯誤,指定需要2個參數,當我只有一個參數的佔位符值。PHP-PDO Prepared statment,「警告:PDOStatement :: bindParam()需要至少2個參數」

CODE:

<?php include ('connection.inc.php'); 

class Team { 

    // Remember to switch back to private! 
    private $database; 
    public $statement = 'SELECT * FROM members ORDER BY :full_name'; 
    public $order; 
    public $query; 

    private $result;  

    public function __construct($database, $order) { 
     $this->database = $database; 
     $this->order = $order; 
     $this->query = $this->database->prepare($this->statement); 
     $this->query->bindParam(array('full_name', $this->order)); 
     $this->query->execute();     
    } 

    public function getMember() {   
     $this->result = $this->query->fetch(PDO::FETCH_ASSOC); 
     return $this->result;       
    } 
    public function id() { 
     echo $this->result['id']; 
    } 

    public function fullName() { 
     echo $this->result['full_name']; 
    } 
    public function alias() { 
     echo $this->result['alias']; 
    } 
    public function abilities() { 
     echo $this->result['abilities']; 
    }  

}; 

$test = new Team($database, 'full_name'); 

?> 

ERRORS:

警告:PDOStatement對象:: bindParam()期望至少2個參數,1

致命錯誤給出:帶有消息'SQLSTATE [HY093]的未捕獲異常'PDOException':無效的參數編號:無參數ERS被束縛」

解決方案

感謝@Daerik,我改變了我的bindParam()語句:

$this->query->bindParam(':full_name', $this->order)); 

此刪除這些錯誤。

回答

1

PDOStatement::bindParam (mixed $parameter , mixed &$variable )

$parameter:參數標識符。對於使用命名佔位符的預準備語句,這將是表單的參數名稱:name。對於使用問號佔位符的準備好的語句,這將是參數的1索引位置。

$variable:要綁定到SQL語句參數的PHP變量的名稱。

你需要使用:

$this->query->bindParam(':full_name', $this->order); 

欲瞭解更多信息,請閱讀PDOStatement::bindParam

+0

謝謝,刪除錯誤和。但是,當使用'gettMember()'方法迭代sql查詢時,它將接受忽略我的'ORDER BY':full_name''語句並使用'id'列對條目進行排序。這是我準備好的陳述中的錯誤嗎? –

+1

@ FrederickM.Rogers您將要在'ORDER BY'語句中使用一列。分配一個字符串會將它們全部比較爲相同的值,並默認爲索引。閱讀http://dev.mysql.com/doc/refman/5.7/en/order-by-optimization.html瞭解更多信息。 – Daerik

+0

謝謝你會通讀它並做出必要的調整! –

1

不要使用bindParam()傳遞多個參數,只需使用:

$this->query->execute(array(':full_name' => $this->order)); 

注意:您需要在參數名的:,你需要通過':key' => $value雙。

或者只是一個,不傳遞一個數組,bindParam()需要兩個參數:

$this->query->bindParam(':full_name', $this->order); 
+1

使用'PDOStatement :: execute'時,您不必包含':'。 – Daerik

+1

@Daerik:從未嘗試過,所有手動示例都顯示':parameter',__ input_parameters中的鍵必須與SQL._中聲明的鍵相匹配,但這可能是可能的。 – AbraCadaver

+1

冒號在SQL語句中是必需的,用於指示哪些標識符是佔位符。 'execute()'調用中的冒號是可選的。文檔指定了它們,但是實現足夠聰明,以便在您將它們排除在外時弄清楚您的意思。 – Daerik

相關問題