0

I'm currently trying to create a function where I can control what field and what values get pulled. This is something I had in mind, but it doesn't work. I get no error, it returns an empty array.

public function test ($field, $id) {
  $sql = $this->con->prepare("SELECT ? FROM Content WHERE id=?");
  $sql->bindParam(1, $field);
  $sql->bindParam(2, $id);
  $sql->execute();

  while ($row = $sql->fetch()) {
    echo $row;
  }
}

I'm unsure about the "SELECT ?..." part I'm not 100% sure that is the correct way. The basic idea is I can make a call anywhere like:

< ?php $obj = new handler; $obj->test($_GET['Title'], $_GET['id']); ?> which will echo the Title with the correct id.

Ben Carey
  • 16,540
  • 19
  • 87
  • 169
ejx
  • 469
  • 1
  • 6
  • 20

1 Answers1

1

the way prepared statements work is that the quesry is prepared and then the data for the fields is sent. Because the first '?' refers to an actual part of query it can not be prepared. Workarounds: a) Fetch the whole row and return just the field you need

$this->con->prepare("SELECT * FROM Content WHERE id=?");
//.......
return $row->$field;

b) Insert the field raw into the query (you can use quotes though)

$this->con->prepare("SELECT `{$field}` FROM Content WHERE id=?");

Also if you intend to use it like the way you described it is possible that you be making a whole lot of dduplicate calls to the database

Dracony
  • 842
  • 6
  • 15
  • 2
    Who -1'd this, and why? If you're going to -1 something, **tell the person who wrote it how they can improve** – Jimbo Feb 01 '13 at 12:52