I’m writing a function that takes two parameters, the first being the id of a user (which defaults to %) and the second being which fields should be retrieved (which defaults to *). The first parameter works fine, but for some reason when I try using an asterisk as the value of the parameter for the prepared statement I get odd results (listed below). Is there any reason why I can’t use an asterisk in a prepared statement but can use a percent sign? My function is below:
public function getMembers($id = '%', $fields = '*') {
$sql = 'SELECT ?
FROM members
WHERE members.member_id LIKE ?;';
return $this->executeQuery($sql, array($fields, $id));
}
and here is the executeQuery function:
public function executeQuery($query, array $parameters = array(), $fetch_type = PDO::FETCH_ASSOC) {
$result = array();
$sth = $this->handle->prepare($query);
if($sth->execute($parameters)) {
while($row = $sth->fetch($fetch_type)) {
array_push($result, $row);
}
}
return $result;
}
And finally the result if I use the default asterisk:
Array
(
[0] => Array
(
[*] => *
)
)
Parameters behave as values. Field names are identifiers, not values, so what you’re doing ends up acting like:
which is, of course, useless.
If you need to pass field names into a PDO query, you will need to escape them appropriately and interpolate them into the query. Ideally, though, your code should be structured such that this is not necessary.