我试图创建一个函数,我只需要<?php echo $user_args['user_id']; ?>
来调用变量。如果用户已登录,我可以使用此格式。我无法在PDO中使用此功能。
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
$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
我的代码中有哪些错误导致其无效?谢谢!
答案 0 :(得分:2)
$ db
function user_args($db) {
// ...
}
还在函数调用中添加$ db:
$user_args = user_args($db, 'user_id',
'username',
'email',
'password');