如何将准备好的语句和参数化查询的PDO结果返回到网页?

时间:2017-07-02 20:01:59

标签: php mysql pdo

我使用以下答案来修补SQLi(How can I prevent SQL injection in PHP?),但是,虽然建立了与数据库的连接,但页面仍然是空白的,就像没有返回数据一样。这是一个例子:

        public function getPlayerInfo($name){
        $stmt = $this->db->prepare("SELECT * FROM playerinfo WHERE PlayerName = ':name'"); 
        //$stmt->execute(); 
        return $stmt->execute(array('name' => $name)); } // I tried using this but it didnt work, information page is left blank
        return $stmt->fetchAll(PDO::FETCH_ASSOC); } // This one used to work before I applied the patch

我正在使用播放器信息页面中的功能来显示他的信息。我怎样才能使用它来返回一个可以通过foreach在该页面上读取的数组?

谢谢!

1 个答案:

答案 0 :(得分:1)

删除占位符:name周围的单引号,您准备好的语句应如下所示:

$stmt = $this->db->prepare("SELECT * FROM playerinfo WHERE PlayerName = :name"); 

这是完整的getPlayerInfo()方法,

public function getPlayerInfo($name){
    $stmt = $this->db->prepare("SELECT * FROM playerinfo WHERE PlayerName = :name"); 
    $stmt->execute(array('name' => $name));
    return $stmt->fetchAll(PDO::FETCH_ASSOC); 
}

此问题已在此处记录,http://php.net/manual/en/pdo.prepare.php#111458