在CI中创建登录表单时,无法将会话值从视图传递到控制器

时间:2018-04-14 04:46:12

标签: php codeigniter

controller:Add_user.php

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Add_user extends CI_Controller {
    function __construct() 
    {
        parent :: __construct();
        $this->load->helper(array('form', 'url', 'captcha', 'email'));
        $this->load->model('ads_data');
    }
    public function home()
    {
        $data['admin_id'] = $this->session->userdata('admin_id');
        print_r($data['admin_id']);
    }
}

view:login.php

<?php
    if($this->input->post('submit'))
    { 
        $username = $this->input->post('username');
        $password = $this->input->post('password');

        $this->db->select('username,password');
        $this->db->from('admin');
        $where = "username='$username' and password = '$password'";
        $this->db->where($where);
        $query = $this->db->get();
        $result = $query->result_array();
        $num = $query->num_rows();
        if($num > 0)
        {
            $this->db->select('username,password,admin_id');
            $this->db->from('admin');
            $where = "username='$username' and password = '$password'";
            $this->db->where($where);
            $query = $this->db->get();
            $result = $query->result_array();
            $this->session->set_userdata('admin_id',$result);
            if($result == true)
            {
                redirect('add_user/home');
            }
        }
        else
        {
            echo "<p style='color: red;font-weight: 400;margin-right: 60px;'>Wrong email id or password! </p>";
        }
    }
?>
<form class="form-signin" method="post">
    <input type="text" name="username" id="username" class="form-control" placeholder="username" required autofocus>
    <input type="password" name="password" id="password" class="form-control" placeholder="Password" required>
    <input type="submit" id="submit" name="submit" class="btn btn-lg btn-primary btn-block" value="Sign In">
</form>

在这段代码中,我在我的视图中创建了一个登录表单,当我点击提交按钮时,它在add_user / home上重定向我,因为我在代码上方提到并且还在控制器内部传递会话值但是现在我是无法传递会话值。它正在使用localhost但不能正常工作。那么,我如何打印会话值或传递给控制器​​?

来自评论

$config['sess_driver'] = 'files'; 
$config['sess_cookie_name'] = 'ci_session'; 
$config['sess_expiration'] = 7200; 
$config['sess_save_path'] = BASEPATH . 'cache/'; 
$config['sess_match_ip'] = FALSE; 
$config['sess_time_to_update'] = 300; 
$config['sess_regenerate_destroy'] = FALSE; 

1 个答案:

答案 0 :(得分:0)

为什么在使用CI时在视图中添加了登录代码。首选方法是使表单标记的action属性将表单数据发送到控制器。然后,您可以执行验证以及设置会话变量。

<form method = 'post 'action = '<?php echo base_url()."/Controller/function"?>'