0

To query in different cells of a given table I want to use one function where I pass the cell´s name to query, like this :

$cell = 'frames';

$query = $this->db->prepare('SELECT :cell FROM time_table WHERE time = :time ');
$query->bindValue(':cell', trim($cell), PDO::PARAM_STR);
$query->bindValue(':time', trim($time), PDO::PARAM_STR);
$success = $query->execute();
$query_result = $query->fetchAll();

 print_r($query_result);

But instead of getting the content of the frames I get the cell' name, which is frames.

What do I need to do to get the content ?

Ben
  • 677
  • 5
  • 19

1 Answers1

-1

Simple answer: It's not possible. Placeholders can only insert values in the prepared statement. To workaround this issue, please use PDO::quote:

$cell = 'frames';

$query = $this->db->prepare('SELECT '.$this->db->quote(trim($cell)).' FROM time_table WHERE time = :time ');
$query->bindValue(':time', trim($time), PDO::PARAM_STR);
$success = $query->execute();
$query_result = $query->fetchAll();

print_r($query_result);
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
tillz
  • 2,108
  • 15
  • 21
  • What about SQL injections ? – Ben Sep 16 '15 at 16:44
  • @Ben That's why you should use it, instead of directly injecting the value. Quote will take care of any characters that would allow an sql injection, if properly used - Please have a look at the Security Warning in the (now correctly ;-) ) linked manual! – tillz Sep 16 '15 at 16:47