-1

i have this method

public function getArticles($order){
        $stmt = $this->db->prepare("SELECT * FROM articles ORDER BY :order");
        $stmt->bindParam('order',$order);
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $results;
    }

that im calling like this

$articles->getArticles('created DESC');

but when i trying to do 'created ASC' it will not change the order? i have tryed with two $vars and with backtics around the column, but i cant get it to work and i do not get any errors to work with it just pulls the rows in the same order every time.

Found the solution on https://phpdelusions.net/pdo

$orders  = ["name","price","qty"];
$key     = array_search($_GET['sort'], $orders);
$orderby = $orders[$key];
$direction = _GET['direction'] == 'DESC' ? 'DESC' : 'ASC';
$query   = "SELECT * FROM `table` ORDER BY $orderby $direction";

1 Answers1

2

Your query uses a bind variable to name a column. You Can't Do That™.

Column names, including the ones in ORDER BY clauses, have to be specified as part of the text of the query.

O. Jones
  • 103,626
  • 17
  • 118
  • 172