-3

So in my init.php file it checks to see if the user is logged in, that requires a function called user_data($username)

Here's what they contain.

init.php

if (logged_in() === true) {
    $session_user_id = $_SESSION['user_id'];
    $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'first_name', 'last_name', 'email', 'coins', 'host', 'bets', 'online', 'multi');
    $user_id = $user_data['user_id'];   
    if (user_active($user_data['username']) === false) {
        session_destroy();
        header('Location: index.php');
        exit();
    }
}

The function user_data() is

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) . '`';
    $sql = sprintf('SELECT `%s` FROM `users` WHERE `id` = ? LIMIT 1', $fields);
    $stmt = $dbh->prepare($sql);
    $stmt->execute(array($user_id));
    $data = $stmt->fetch(PDO::FETCH_ASSOC);

    return $data;
}
}

I get the error PHP Fatal error: Call to a member function prepare() on a non-object is this because I'm not calling the function with $db or is my function just incorrect?

  • 4
    `$dbh` isn't in scope in `user_data()` – andrewsi May 10 '13 at 15:25
  • There's only one `$dbh` variable in all this code, and it's never being *declared* anywhere; much less within the scope of the function. – deceze May 10 '13 at 15:28
  • 1
    duplicate of http://stackoverflow.com/questions/16473791/php-pdo-issues-translating-from-mysql – Your Common Sense May 10 '13 at 15:28
  • And *somewhat* of http://stackoverflow.com/questions/16455378/pdo-with-mysql-not-working-in-email-activation where the OP had the code to pass the connection into function already, but lost it somewhere in the process :) – Your Common Sense May 10 '13 at 15:30
  • Thanks again detective common sense ;) I'm a huge beginner with all of this, and appreciate you letting me know every time. – user2305310 May 10 '13 at 15:34

1 Answers1

2

You haven't connected to the database. You should have a PDO database connection inside the user_data function, or global, or pass it in.

Eran
  • 387,369
  • 54
  • 702
  • 768
Ascherer
  • 8,223
  • 3
  • 42
  • 60
  • The connection is there, it's included outside of the function from the init.php – user2305310 May 10 '13 at 15:29
  • 2
    In that case just add "global $dbh" right after declaring the function. Functions don't have access to global resources unless you expressly mark them as global.. – Mustapha May 10 '13 at 15:33