php - converting to PDO, problems -
so working on converting old tutorial did while mysql
pdo
. way can better understand concepts. seem of run wall however. following function giving me 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 members 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 calling 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 error
catchable fatal error: object of class pdo not converted string in c:\xampp\htdocs\core\functions\users.php on line 12
so more line commented on in function above
$fields = '`' . implode('`, `', $func_get_args) . '`';
i don't see why line causing error. have no idea how fix it. appreciated.
func_get_args() returns all arguments of function. unset() 0th element, have two elements need remove start of args. show example below of using array_slice() start element 2.
also, function has glaring sql injection vulnerability, interpolating list of column names directly sql select-list. should whitelist input against list of columns of users table, make sure input doesn't contain don't expect.
function user_data($user_id, pdo $db) { // hardcoded list of columns in users table; use whitelist $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 users 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()); } } }
Comments
Post a Comment