0

I'm trying to create a function where I can simply do <?php echo $user_args['user_id']; ?> to call a variable. If a user is logged in I can use this format. I can't get this function working in PDO though.

I'm getting this error message:

Notice: Undefined variable: db in /Applications/XAMPP/xamppfiles/htdocs/app/user/func/user.func.php on line 35

    Fatal error: Call to a member function prepare() on a non-object in /Applications/XAMPP/xamppfiles/htdocs/app/user/func/user.func.php on line 35

This is the function I'm trying to do:

$db = new PDO("mysql:host=$servername; dbname=$database", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

function user_args() {

        $user_id = $_SESSION['user_id'];

        $args = func_get_args();
        $fields = implode(', ', $args);
        $query = $db->prepare("SELECT * FROM users WHERE user_id = :user_id");
        $query->bindParam(':user_id', $user_id);
        if($query->execute()) {
            $query_success = $query->fetch(PDO::FETCH_ASSOC);
            foreach($args as $arg) {
                $args[$arg] = stripslashes($query_success[$arg]);
                }
            return $args;
            }

        }

    $user_args = user_args('user_id',
                            'username',
                            'email',
                            'password');

    echo $user_args['user_id']; // <- The function isn't working so I can't do this

What's wrong in my code that's making this not work? Thanks!

Graham
  • 309
  • 1
  • 13

1 Answers1

2

$db is missing inside the function

function user_args($db) {

       // ...
        }

also add $db in the function call:

$user_args = user_args($db, 'user_id',
                        'username',
                        'email',
                        'password');
pavlovich
  • 1,885
  • 12
  • 19
  • When I do this, it gives me this error: Catchable fatal error: Object of class PDO could not be converted to string in /Applications/XAMPP/xamppfiles/htdocs/app/user/func/user.func.php on line 19 – Graham Nov 28 '15 at 09:07
  • @Graham, can you write here line 19 of your script? – pavlovich Nov 28 '15 at 09:12
  • $fields = implode(', ', $args); – Graham Nov 28 '15 at 09:13
  • 1
    insert this line `array_shift($args);` before that line with implode. It will remove first PDO element which is unnecessary there – pavlovich Nov 28 '15 at 09:19