Reputation: 1094
I'm making a function which returns the requested fields of certain user connected to a user ID, my current code is this:
<?php
function getUserData($id = "current", $field = "username"){
global $database;
if($id == "current"){
$id = $_SESSION['userID'];
}
$query = $database->prepare("SELECT :field FROM `users` WHERE `ID` = :ID LIMIT 1;");
$query->bindParam(":ID",$id);
$query->bindParam(":field",$field);
$query->execute();
while($row = $query->fetch(PDO::FETCH_BOTH)){
print_r($row);
}
//return $username;
}
?>
if the $id
value is kept empty it looks for the currently logged in ID, which works fine. Same for the $field
if that is empty, it looks just for the username connected to the ID the problem is in the
$query->bindParam("field",$field);
.. for some reason this does not work and while using this the print_r returns this:
Array ( [username] => username [0] => username )
while the exact same query works when using it like this:
$query = $database->prepare("SELECT $field FROM
usersWHERE
ID= :ID LIMIT 1;");
What am I doing wrong?
Upvotes: 3
Views: 352
Reputation: 3858
You're binding a field name, so your query will become like this:
SELECT 'username' FROM `users` WHERE `ID` = 'X' LIMIT 1;
This won't work, you can't bind a field name like this. you will have to pass field names as php variables directly without binding them.
Check out this: Can PHP PDO Statements accept the table or column name as parameter?
It might help you.
Upvotes: 4