Mysqli query returning wrong values

I am creating a function that returns the requested fields of a specific user connected to a user id, my current code is:

<?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 value $id

is left blank, it looks for the current id, which works fine. Same for $field

, if empty, it looks just for the username associated with the id, the problem is in $query->bindParam("field",$field);

.. for some reason it doesn't work, and while print_r returns this:

Array ( [username] => username [0] => username )

while the same query works when used like this:

$query = $database->prepare("SELECT $field FROM

user WHERE

ID= :ID LIMIT 1;");

What am I doing wrong?

+3


source to share


1 answer


You are binding the field name, so your request will look like this:

SELECT 'username' FROM `users` WHERE `ID` = 'X' LIMIT 1;

      

It won't work, you can't bind the field name like this. you will have to pass the field names as php variables directly without linking them.



Note this: Can PHP PDO expressions take a table or column name as a parameter?

This might help you.

+4


source







All Articles