Reputation: 83
I want get the session fname for welcome admin site(crud), for a session username i already have it because it already delclare $_SESSION['username'] = $this->input->post('username');
, My question how to make a session fname from database?
Database SQL
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(30) NOT NULL,
`password` varchar(32) NOT NULL,
`fname` varchar(30) DEFAULT NULL,
`lname` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
)
Controller
<?php if(!defined('BASEPATH')) exit('Tidak ada akses!');
class C_login extends CI_Controller{
function __construct(){
session_start();
parent::__construct();
$this->load->model('m_user');
}
public function index(){
if(isset($_SESSION['username'])){
redirect('crud');
}
$this->form_validation->set_rules('username','Username','required');
$this->form_validation->set_rules('password','Password','required');
if ($this->form_validation->run() == TRUE){
$this->load->model('m_user');
$result = $this->m_user->cek_login(
$this->input->post('username'),
$this->input->post('password')
);
if($result == TRUE){
$_SESSION['username'] = $this->input->post('username');
redirect('crud');
}
}
$this->load->view('login/v_form');
}
public function daftar(){
$data = array(
'username' => $this->input->post('username'),
'password' => md5($this->input->post('password)')),
'fname' => $this->input->post('fname'),
'lname' => $this->input->post('lname')
);
$this->m_user->tambah_user($data);
$this->load->view('login/v_daftar',$data);
}
public function logout(){
session_destroy();
$this->index();
}
}
Model
<?php if(!defined('BASEPATH')) exit('Tidak ada access!');
class M_user extends CI_Model{
function __construct(){
parent::__construct();
}
function cek_login($username,$password){
$query = $this->db->where('username',$username)
->where('password',md5($password))
->limit(1)
->get('users');
if ($query->num_rows() > 0){
return $query->row_array();
}
else{
return FALSE;
}
}
function tambah_user($data){
return $this->db->insert('users', $data);
}
}
Upvotes: 0
Views: 180
Reputation: 1847
first off, you should not post the input into the session, you should first validate it against the db. Your inputs should be sanitized for SQL injections etc.
I, personally, would do it with the CI's session library (you need to autoload it in the autoload config)
Then it is something along these lines in your model, or you could send the $data to the controller and add it to the session from there.
if ($query->num_rows() === 1){
$row = $query->row();
$data = array (
'username'=> $row->id,
'fname' => $row->fname
);
$this->session->set_userdata($data);
}
Then, if you want to use the session you need to call it like so
echo $this->session->userdata('username');
This will echo your user's id which you can use as you wish.
Upvotes: 1