0

I need to convert this:

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 FROM users WHERE user_id = $user_id"));

        return $data;
    }

}

to this:

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) . '`';
        $query = $db->prepare("SELECT $fields FROM `admin` WHERE `id` = :user_id");
        $query->bindParam(":user_id", $user_id);
        $query->execute();
        $data = $query->fetch(PDO::FETCH_ASSOC);
        print_r ($data);
    }
}

Problem is I cannot get the second bit to work. I keep getting this:

Fatal error: Call to a member function prepare() on a non-object in /home/ds4887/public_html/silverjet/v1.20/admin/core/functions/main.php on line 39

If you need any other information I will be more than glad to provide it. If not possible than can somebody please so me the correct method to do this. THe top works, the bottom needs to work.

Thanks in advance

3 Answers3

3

$db is not defined within user_data(). As such, $db->prepare() fails with the error.

You need to establish your PDO connection and ensure user_data() has access to $db either by:

Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
  • I really want to give you an upvote but you used the "G" word – Phil Sep 05 '13 at 03:07
  • @Phil, I almost didn't. Hence it was the last option. I also tagged it as *poor design*. I try to be thorough. Otherwise, it seems the opposite happens - someone down votes. – Jason McCreary Sep 05 '13 at 11:38
0

My guess is you have a problem with variable scoping. You should pass the $db variable to the function (preferred), or use global $db declaration to import the variable from the global scope to the function's scope.

Your previous function only worked because you were using mysql_query() in a sort of hackish fashion, without specifying the connection for the query. The default behavior in this case is to use the most recently opened mysql resource link globally, so it just happened to work.

Mike Brant
  • 70,514
  • 10
  • 99
  • 103
0

You're not passing in a value for $db for this line:

  $query = $db->prepare("SELECT $fields FROM `admin` WHERE `id` = :user_id");

$db is the connection resource set up when you connected to the database. You need it in PDO, but you can get away without it with mysql because mysql assumes the last connection you established.