0

i have a function that returns user data from the database. But I want to return only the selected row, for instance username, so i created an array for that, giving the option to echo $userdata['anything']. see the code:

$session_user_id = $_SESSION['user_id'];
    $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name'); } 

and

function user_data($user_id){

$pdo = new PDO("mysql:host=localhost;dbname=MYDATABASE;", "MYUSERNAME", "MYPASSWORD");
$data = array();
$user_id = (int)$user_id;

$func_num_args = func_num_args();
$func_get_args = func_get_args();

if ($func_num_args > 1) {
    unset($func_get_args[0]);
    $fields = '`' . implode(', ', $func_get_args) . '`';
    echo $fields;
    $stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");
    $stmt->execute(array(':user_id' => $user_id, ':fields' => $fields));
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);

    print_r($data);
}
}

The problem is that this doesn't work. It returns

Array ( [0] => Array ( [`user_id, username, password, first_name, last_name`] => `user_id, username, password, first_name, last_name` ) )

However, replacing :fields with for instance 'username' does work. Is it possible to use this implode?

1 Answer 1

1

Change:

$stmt = $pdo->prepare("SELECT :fields FROM `users` WHERE `user_id` = :user_id");

to:

$stmt = $pdo->prepare("SELECT $fields FROM `users` WHERE `user_id` = :user_id");

and remove $fields from the execute parameter array.

Parameterized placeholders are only for values.

UPDATE

Also this line is wrong:

$fields = '`' . implode(', ', $func_get_args) . '`';

This will output a ` outside the the field list rather than each column name.

Try removing them like this:

$fields = implode(', ', $func_get_args);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply! I tried changing :fields to $fields before, however this gives an empty array as output, exactly this - array()
I noticed something else wrong, see my updated answer.
U are a genius, sir. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.