You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用CodeIgniter时持续提示“未定义变量”错误求助

Fixing the "Undefined Variable" Error in Your CodeIgniter Login Controller

Hey there, let's break down why you're hitting that frustrating undefined variable error and fix it step by step.

1. The Root Cause of the Undefined Variable

Looking at your code snippet:

$data['user_data'] = $this->Login_model->login_user($username, $password);
echo $user_data->fname; // Here's the problem!

You’ve stored the user data in the $data['user_data'] array index, but you’re trying to access a standalone $user_data variable that doesn’t exist. The $data array in CodeIgniter is primarily meant for passing data to views, but if you want to use the data directly in your controller, you need to reference it correctly.

2. Quick Fixes

Option A: Assign to a Direct Variable (Cleanest for Controller Use)

Store the model’s result in a dedicated variable first, then reuse it throughout your controller logic:

// Store the login result once
$user_data = $this->Login_model->login_user($username, $password);

if ($user_data) { // Verify login was successful
    echo $user_data->fname;
    
    // Fix your session setup (no typos!)
    $user_array = array(
        'fname' => $user_data->fname,
        'level' => $user_data->level,
        'logged_in' => true
    );
    $this->session->set_userdata($user_array);
}

Option B: Access from the $data Array

If you need to keep the data in $data (to pass to a view later), reference it using the array index:

$data['user_data'] = $this->Login_model->login_user($username, $password);

if ($data['user_data']) {
    echo $data['user_data']->fname;
    // ... rest of your session code
}

3. Bonus: Eliminate Duplicate Model Calls

You’re calling $this->Login_model->login_user($username, $password) twice—once in the if condition, once when assigning the data. This runs unnecessary database queries. Storing the result once (like in Option A) avoids this wasteful repetition.

4. Double-Check Your Model’s Return Type

Make sure your login_user method returns either an object (using CodeIgniter’s row() method) or an array (using row_array()). If it returns an array, you’ll need to use bracket notation instead of the arrow:

// If model returns an array instead of an object
echo $user_data['fname'];

5. Tiny Session Typo Fix

In your commented-out session code, you had a typo: $this->session->set_userdata($user_ar... should be $user_array (the variable you defined).


内容的提问来源于stack exchange,提问作者phishyman2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:21:43