PHP MySQLi准备的语句在绑定不同参数时给出相同的结果


PHP MySQLi prepared statement giving same result when binding different parameter



我正在努力制作一个类,可以用来显示我的5个最新帖子和4个最受欢迎的帖子。我使用一个预先准备好的语句来完成这项工作,保留ORDERBY语句以包含两个不同的参数

问题是,当我运行这个程序时,我得到的结果是相同的(帖子的顺序相同)。我在主页上运行的代码是这样的:

<?php
    $test = new SideBar();
    echo $test->recent();
    echo $test->popular(); // returns the same as recent() for some reason
?>

这就是

class SideBar
{
    // Storing the names of the database table columns
    private $id = 'n';
    private $rating = 'mean';
    private $stmt;
    private $result;
    public function __construct()
    {
        global $mysqli;
        $this->stmt = $mysqli->prepare("SELECT n,title,date
                                        FROM claims
                                        WHERE active = 1 
                                        ORDER BY ? DESC
                                        LIMIT 5");
    }
    public function recent()
    {
        $this->result = "";
        return $this->build($this->id);
    }
    public function popular()
    {   
        $this->result = "";
        return $this->build($this->rating);
    }
    private function build($order)
    {
        $this->stmt->bind_param('s',$order);
        $this->stmt->execute();
        $this->stmt->bind_result($n, $title, $date);
        while($this->stmt->fetch())
        {
        $this->result .= '<a href="[mydomain]?id='.$n.'">';
        $this->result .= $title.' '.$date;
        $this->result .= "</a>'n";
        }
        return $this->result;
    }
    public function __destruct()
    {
        $this->stmt->close();
    }
}

显然,您不能将列名绑定到ORDERBY子句。相反,您可以在recentpopular函数中形成必要的查询,并将prepare pdo语句移动到build函数中。以下是修改:

public function __construct()
    {
    }
    public function recent()
    {
        $this->result = "";
        $q="SELECT n,title,date
                                        FROM claims
                                        WHERE active = 1 
                                        ORDER BY id DESC
                                        LIMIT 5"
        return $this->build($q);
    }
    public function popular()
    {   
        $this->result = "";
        $q="SELECT n,title,date
                                        FROM claims
                                        WHERE active = 1 
                                        ORDER BY mean DESC
                                        LIMIT 5"
        return $this->build($q);
    }
    private function build($query)
    {
        global $mysqli;
        $stmt = $mysqli->prepare($query)
        $stmt->execute();
        $stmt->bind_result($n, $title, $date);
        while($stmt->fetch())
        {
        $this->result .= '<a href="[mydomain]?id='.$n.'">';
        $this->result .= $title.' '.$date;
        $this->result .= "</a>'n";
        }
        return $this->result;
    }