query prepared in php does not work (no error)

1

I'm trying to execute this query but it does not give me any errors but it does not work for me, it simply does not order anything:

$sql = 'SELECT * FROM productos ORDER BY :orden';
$stmt = $this->BD->prepare($sql);
$params = array(':orden'=>'titulo');
$stmt->execute($params);
return $stmt->fetchAll();
    
asked by Theasker 15.11.2016 в 15:17
source

2 answers

2

Identifiers and operators do not support the capabilities of prepared queries. These elements must exist in the original query. Imagine if not the following case:

$sql = ":a :b :c :d";
$params = array(':a'=>'SELECT',':b'=>'*',':c'=>'FROM',':d'=>'productos');
$stmt = $this->BD->prepare($sql);
$stmt->execute($params);

Or, already put:

$sql = ":a";
$params = array(':a'=>'SELECT * FROM productos');
$stmt = $this->BD->prepare($sql);
$stmt->execute($params);

As you wish that the order can be modified according to convenience you can make use of the PHP variables so that the original query has its identifiers duly indicated:

$orden = 'titulo';
$sql = "SELECT * FROM productos ORDER BY $orden";
$stmt = $this->BD->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
    
answered by 15.11.2016 в 15:25
0

Bastaria con

$orden = 'titulo';
$sql = 'SELECT * FROM productos ORDER BY $orden';
    
answered by 15.11.2016 в 15:32