dtlygweb2017 2013-07-03 19:41
浏览 48
已采纳

使用PDO的未定义变量 - 混淆

I'm just starting to get to grips with using PDO over mysql_ and I'm currently in the process of converting all of the mysql_ functions into PDO. The problem I have is that I am completely stumped with these functions. The purpose of these is to take the user_id from the $_SESSION created on login and return their data from the database using that user_id. However, I'm getting the error:

Undefined variable: user_data

each time I try to check whether something is true, for example if admin = 1. This is the user_data function:

function user_data($user_id) {
    global $con;
    $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 = "SELECT $fields FROM `users` WHERE `user_id` = $user_id";
        $result = $con->prepare($data);
        $result->execute();
        $user_data = $result->fetch();

        return $user_data;
    }
}

This piece of code should call that function and destroy the session if banned = 1:

if (logged_in() === true) {
    $session_user_id = $_SESSION['user_id'];
    $user_data = user_data($session_user_id, 'user_id', 'username', 'password', 'email', 'password_recovery', 'moderator', 'admin');
    if (user_banned($user_data['username']) === true) {
        session_destroy();
        header('Location: pts.php');
        exit();
    }
}

and this is an example of where I am trying to use the $user_data variable:

<?php if ($user_data['moderator'] == 1)

I apologise if this is difficult to understand as I am a noob when it comes to coding and I'm not particularly good at explaining things. If you need any more code please just ask, I am happy to provide it.

Thank you everyone.

  • 写回答

2条回答 默认 最新

  • douju1852 2013-07-03 19:46
    关注

    You only define $user_data if the user is logged in. You need to make sure that $user_data exists before you try to access it.

    if (!empty($user_data) && $user_data['moderator'] == 1)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器