1

我按照 Code Factory 上的教程为 codeigniter 编写了一个简单的登录脚本。我现在可以登录,但是当我想通过代码向用户显示时

Welkom: <?php echo $username ?>!

我收到错误消息:未定义的变量:用户名

我不知道问题是什么,所以我会在您要求时发布我的代码。

谢谢

编辑:

我的用户模型。

  <?php
    Class User extends CI_Model
    {
     function login($username, $password)
     {
       $this -> db -> select('id, username, password');
       $this -> db -> from('users');
       $this -> db -> where('username', $username);
       $this -> db -> where('password', MD5($password));
       $this -> db -> limit(1);

       $query = $this -> db -> get();

       if($query -> num_rows() == 1)
       {
         return $query->result();
       }
       else
       {
         return false;
       }
     }
    }
    ?>

我的登录控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   $this->load->helper(array('form'));
   $this->load->view('login_view');
 }

}

?>

我的家庭控制器:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start(); //we need to call PHP's session object to access it through CI
class Home extends CI_Controller {

 function __construct()
 {
   parent::__construct();
 }

 function index()
 {
   if($this->session->userdata('logged_in'))
   {
     $session_data = $this->session->userdata('logged_in');
     $data['username'] = $session_data['username'];
     $this->load->view('home_view', $data);
   }
   else
   {
     //If no session, redirect to login page
     redirect('login', 'refresh');
   }
 }

 function logout()
 {
   $this->session->unset_userdata('logged_in');
   session_destroy();
   redirect('home', 'refresh');
 }

}

?>
4

3 回答 3

2
Welkom: <?php echo (isset($username))?$username :"Guest" ?>!
于 2013-02-20T09:05:50.147 回答
0

尝试更换

Welkom: <?php echo $username ?>!

和:

Welkom: <?php echo (isset($data['username'])) ? $data['username'] : "Guest"; ?>!
于 2013-02-20T09:40:03.597 回答
0

我会在 Home 类中做进一步检查,看看是否

$data['username'] = $session_data['username'];

已经设置好了。试试这个:

$session_data = $this->session->userdata('logged_in');
$data['username'] = $session_data['username'];
//$this->load->view('home_view', $data);
echo "username: " . $data['username']; exit;
于 2013-02-20T09:44:18.743 回答