php - PDO alternative to mysql_ for getting field info -
when learned php, learned apparently older guides , have been using mysql_ functions. i'm switching on pdo , have function want keep can't quite figure out how change it. mysql_ function.
function getfield($field){ $query = "select $field users id='".$_session['user_id']."'"; if($query_run = mysql_query($query)){ if ($query_result = mysql_result($query_run, 0, $field)){ return $query_result; } } }
and can field want. it's using mysql_ stuff hear deprecated , on way out. function gets session id when log in, , using session info, gathers information user.
here quick example of function using pdo. i've left comments in code grasp idea.
function getfield($field) { // assuming obtained connection here. // purpose of showing example name database connection variable $db // first check if have user_id in our session, , sanitize it. // never query database unsanitized data. $userid = isset($_session['user_id']) ? filter_var($_session['user_id'], filter_sanitize_number_int) : null; // if user_id not presented, don't need query database @ all. return null or whatever suits needs if( ! $userid ) { return null; } // build query $sql = sprintf( "select `%s` `users` `id` = :userid limit 1", $field ); // prepare statement executed // more read prepared statements: http://php.net/manual/en/pdo.prepare.php $query = $db->prepare($sql); // pass user id our prepared query // more read binding parameters: http://php.net/manual/en/pdostatement.bindparam.php $query->bindparam(':userid', $userid); // execute query $query->execute(); // return single result return $query->fetch(pdo::fetch_assoc); }
if have questions, don't hesitate ask.
- update per op comment -
using above function end getting array result following reasons:
->fetch()
combinedpdo::fetch_assoc
option return array single item in if result being found.key
in array in case field name.
now can either access value this:
$result = getfield('username'); print $result['username'];
or in function:
$result = $query->fetch(pdo::fetch_assoc); if( isset($result[ $field ] ) { return $result[ $field ]; } return null;
Comments
Post a Comment