So I am working on converting an old tutorial I did a while back from mySQL
to PDO
. This way I can better understand the concepts. I seem to of run into a wall however. The following function is giving me an error
function user_data($user_id, $db) {
$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) . '`'; // !! LINE 12
try {
$sql = sprintf('SELECT %s FROM members WHERE id = ?', $fields);
$stmt = $db->prepare($sql);
$stmt->execute(array($user_id));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $data;
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
this is where I am calling the function
<?php
session_start();
require 'database/connect_db.php';
require 'functions/users.php';
if (signedIn() === true) {
$session_id = $_SESSION['id'];
$user_data = user_data($session_id, $db, 'email', 'password', 'role', 'name', 'company', 'title', 'phone', 'address', 'city', 'zip', 'state', 'ext', 'pic');
echo $user_data['name'];
}
?>
this is my error
Catchable fatal error: Object of class PDO could not be converted to string in C:xampphtdocscorefunctionsusers.php on line 12
So more specifically this line as commented on in the function above
$fields = '`' . implode('`, `', $func_get_args) . '`';
I don’t see why this line is the causing this error. I also have no idea how to fix it. Any help is appreciated.
Advertisement
Answer
func_get_args() returns all the arguments of the function. You unset() the 0th element, but you have two elements you need to remove from the start of the args. I show an example below of using array_slice() to start with element 2.
Also, your function has a glaring SQL injection vulnerability, interpolating the list of column names directly into your SQL select-list. You should allowlist the input against a list of all the columns of your users table, to make sure the input doesn’t contain something you don’t expect.
function user_data($user_id, PDO $db) {
// hardcoded list of the columns in the users table; use this as an allowlist
$all_users_columns = array('first_name', 'last_name', 'email', /* etc. */);
$columns = array_intersect(array_slice(func_get_args(), 2),
$all_users_columns);
if($columns) {
$column_list = implode(",",
array_map(function($col) { return "`$col`"; }, $columns));
try {
$sql = sprintf('select %s from users where user_id = ?', $column_list);
$stmt = $db->prepare($sql);
$stmt->execute(array((int)$userid));
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $data;
} catch(PDOException $e) {
die($e->getMessage());
}
}
}