2016-12-15 89 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

相关问题