tags:

views:

90

answers:

1

Having problem with binding parameters to PDO statement. "orderBy" seems not to be passed to query and results are not ordered as suppose to. When I use "price" in query itself all is good but cannot bind paremeter via bindParam. The code is:

class Products
{
 const ORDER_BY_NAME="name";
 const ORDER_BY_PRICE_PER_UNIT="price_per_unit";
 const ORDER_BY_PRICE="price";
 const ORDER_BY_MINIMUM_QUANTITY="minimum_quantity";

 // function returns array of all products

 public function getAllProducts($orderBy)
 { 
  $db=Registry::getVariable("db");

  $pdoStatement=$db->prepare("SELECT name, minimum_quantity, price_per_unit, price, id FROM products ORDER BY :orderBy;");

  $pdoStatement->bindParam(":orderBy",$orderBy,PDO::PARAM_STR);

  $pdoStatement->execute();

  return $pdoStatement->fetchAll(PDO::FETCH_ASSOC);
 }
}

and later on calling

 $products=new Products();

 echo $products->getAllProducts(Products::ORDER_BY_PRICE);

why my bindParam(":orderBy",$orderBy,PDO::PARAM_STR); dosen't seem to be used in query? any help would be much appreciated :)

+1  A: 

Parameter binding is intended to be used with values. ORDER BY is actually followed by a field name, not a string.

nuqqsa
See http://stackoverflow.com/questions/2542410/how-do-i-set-order-by-params-using-prepared-pdo-statement
nuqqsa
Right, the problem here is that pdo is inserting the column name with quotes around it.
ryeguy