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条)

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改