3

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 FROMusersWHEREID= :ID LIMIT 1;");

What am I doing wrong?

Azrael
  • 1,094
  • 8
  • 19

1 Answers1

4

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.

Community
  • 1
  • 1
CodeBird
  • 3,883
  • 2
  • 20
  • 35
  • so basicly `$database->prepare("SELECT $field FROM users WHERE ID= :ID LIMIT 1;");` would be my way to go? – Azrael Oct 28 '14 at 09:19
  • @Azrael yes that would be your way to go, you can add some php checks to make sure the fields received actually exist in the table, that's not to face errors with wrong column names. – CodeBird Oct 28 '14 at 09:20
  • The field exists for sure ;) Thanks for your awnser! will mark it once I can ;) – Azrael Oct 28 '14 at 09:21
  • @Azrael Yes it all depends on where you're getting the field name from. if it is hard coded then you don't need testing, if it is entered by a user or something of this sort, then you'll need checks. – CodeBird Oct 28 '14 at 09:22
  • the `$field` value is going to be hardcoded, and the `$id` is dynamic, when left empty it will use the currently logged in ID, otherwise it will use the provided `$id` – Azrael Oct 28 '14 at 09:23