简体   繁体   中英

Need help creating a universal “getter” function in PHP

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM