Php PDO issues translating from mysql -
okay, i'm struggling grasps pdo, after 2 days of trying convert everything.
i'm @ stage of creating array $user_data['???']
, here's i've got.
if (logged_in() === true) { $session_user_id = $_session['user_id']; $user_data = user_data($session_user_id, 'id', 'username', 'password', 'email', 'active', 'coins'); $user_id = $user_data['id']; if (user_active($user_data['username'] === false) { session_destroy(); header('location: index.php'); exit(); } }
so that's way of getting data $user_data['???']
functions go are..
function user_data($user_id){ $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) . '`'; $data = //mysql_fetch_assoc(//mysql_query("select $fields `users` `user_id` = $user_id")); return $data; } } function user_active($username) { $username = sanitize($username); $query = //mysql_query("select count(`user_id`) `users` `username` = '$username' , `active` = 1"); return (//mysql_result($query, 0) == 1) ? true : false; }
i'm pulling hair out trying figure out how convert pdo, can give me help?
also, after convert pdo. simple welcome user simple message of welcome <?php $user_data['username'] ?>, hope enjoy stay!
or need use different method now?
thanks in advance !
so looks of example code impression you're migrating deprecated mysql extension on pdo.
something mysql extension may tripping if don't specify mysql link resource mysql_query
uses lastly created link resource created mysql_connect
. once move using pdo you're going have have pdo connection available in user_data
, user_active
functions. simplest approach create pdo connection in each function, it's terribly repetitive , not solution @ all, works.
there issues sql injection vulnerabilities in code. aside write functions this:
<?php function user_data($user_id){ $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]); // connect db $dsn = 'mysql:dbname=<your_db_name>;host=127.0.0.1'; $user = '<your_db_user>'; $password = '<your_db_user_password>'; $dbh = new pdo($dsn, $user, $password); // request data $fields = '`' . implode('`, `', $func_get_args) . '`'; $sql = sprintf('select %s users user_id = ? limit 1', $fields); $stmt = $dbh->prepare($sql); $stmt->execute(array($userid)); $data = $stmt->fetch(pdo::fetch_assoc); return $data; } } function user_active($username) { $username = sanitize($username); // connect db $dsn = 'mysql:dbname=<your_db_name>;host=127.0.0.1'; $user = '<your_db_user>'; $password = '<your_db_user_password>'; $dbh = new pdo($dsn, $user, $password); $sql = 'select count(user_id) users username = ? , active'; $stmt = $dbh->prepare($sql); $stmt->execute(array($username)); return $stmt->fetchcolumn() == 1; }
hope helps.
Comments
Post a Comment