This question already has an answer here:
I'm trying to make a class that I can use for showing my 5 most recent and 4 most popular posts. I'm doing this using a prepared statement, leaving the ORDER BY statement open for including two different parameters.
The problem is, when I run this, I get the same result for both (the posts come in the same order). The code I run in the main page is this:
<?php
$test = new SideBar();
echo $test->recent();
echo $test->popular(); // returns the same as recent() for some reason
?>
And this is the class:
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>
";
}
return $this->result;
}
public function __destruct()
{
$this->stmt->close();
}
}
</div>