我试图创建一个课程,我可以用它来展示我最近的5个帖子和4个最受欢迎的帖子。我使用预准备语句执行此操作,使ORDER BY语句保持打开状态以包含两个不同的参数。
问题是,当我运行这个时,我得到两个相同的结果(帖子按相同的顺序排列)。我在主页面中运行的代码是:
<?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();
}
}
答案 0 :(得分:0)
显然,您无法将列名绑定到ORDER BY子句。相反,您可以在recent
和popular
函数中形成必要的查询,并将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;
}