adding user id from database to session data in Codeigniter? - php

i am new to CodeIgniter and facing problem in adding user id(after user has logged in) from database to session data here is my code question may be asked before on SOF , after putting all my efforts i am asking this
//login-model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login_model extends CI_Model
{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
//get the username & password from tbl_usrs
public function get_user($usr, $pwd)
{
$sql = "select * from tbl_usrs where username = '" . $usr . "' and password = '" .$pwd . "' ";
$query = $this->db->query($sql);
return $query->num_rows();
}
/* public function set_session($username) {
$sql="SELECT * FROM tbl_usrs WHERE username='".$username."' LIMIT 1 ";
$result=$this->db->query($sql);
$row=$result->row();
$sess_data=array (
'id'=>$row->id,
'username'=>$username,
'is_login'=>TRUE
);
$this->session->set_userdata($sess_data);
} //set_seesion function ends
*/
}
?>
//login controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
print_r( debug_backtrace() );
//ini_set('memory_limit', '-1');
//ini_set('max_execution_time', 3000);
ini_set('display_errors',1);
error_reporting(E_ALL);
class LoginController extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('session');
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->database();
$this->load->library('form_validation');
}
public function index()
{
//load the login model
$this->load->model('login_model');
// $qry=$this->login_model->validate();
//get the posted values
$username = $this->input->post("username");
$password = $this->input->post("password");
$user_id = $this->input->get("user_id");
//set validations
$this->form_validation->set_rules("username", "username", "trim|required");
$this->form_validation->set_rules("password", "password", "trim|required");
if ($this->form_validation->run() == FALSE)
{
//validation fails
redirect('Homecontroller/index'); //make new controller for loading a form again
echo "Validation fails"; // even for no name and passwrd
}
else
{
//validation succeeds
if ($this->input->post('submit') == "Login")
{
//check if username and password is correct
$usr_result = $this->login_model->get_user($username, $password);
if ($usr_result > 0) //active user record is present
{
//set the session variables
$sessiondata = array(
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
'is_login' => TRUE
);
//$this->login_model->set_session($username);
$this->session->set_userdata($sessiondata);
print_r($this->session->all_userdata()); //to check
redirect(base_url("Site/member_area"));
return $username;
}
else
{
$this->session->set_flashdata('msg', '<div class="alert alert-danger text-center">Invalid username and password!</div>');
redirect('Homecontroller/index');
}
}
else
{
redirect('login/home3');
}
}
}
}?>
when i am try to print session data in view i am getting user_id=> empty

None of these variables will be available to you for assignment:
'user_id' => $user_id,
'username' => $username,
'password'=>$password,
The reason for this is that you've used:
$usr_result = $this->login_model->get_user($username, $password);
However, that is only going to be the result of the number of rows returned:
public function get_user($usr, $pwd)
...
return $query->num_rows();
So now, $usr_result will be the number of rows returned, not the data of the user in question.
So, what you should do, is instead set the session data in that login function above return $query->num_rows(); and below $query=.
public function get_user($usr, $pwd){
....
$query = $this->db->query($sql);
$this->session->set_userdata('sessiondata', $query->row_array());
}
Note that as we only retrieve 1 user from our query ever, we also would only ever want to get 1 row back. Furthermore, you're wanting to store an associative array, and not an object, so we use $query->row_array() to get back 1 row formatted as an array where the key is the column name and the value is the columns result.
Now, do a echo '<pre>', print_r($this->session->userdata('sessiondata'), true),'</pre>'; to get a formatted list of that object which contains the array. Then you can map names accordingly.
Sidenote, i would not store the password in an session.

Related

passing user's details in Codeigniter using session [duplicate]

Hi guys I have a User controller and User_model model. I want to be able to retrieve and display a logged in users email and phone number from the database to a view after the user is logged in. any idea how I could go about this would be appreciated and if codes could be written to demonstrate I would be very happy.
MODEL
public function login($username, $password){
//validation
$this->db->select('id, email, username');
$this->db->where('username', $username);
$this->db->where('password', $password);
$this->db->where('status', 1);
$result = $this->db->get('users');
if($result->num_rows() == 1){
return $result->row(0)->id;
} else {
return FALSE;
}
}
public function get_user($username){
$this->db->where('username', $username);
$query = $this->db->get('users');
return $query->result();
}
CONTROLLER:
public function login(){
$data['title'] = 'Login';
$this->form_validation-> set_rules('username', 'Username', 'required');
$this->form_validation-> set_rules('password', 'Password', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
} else {
// fetching user
$username = $this->input->post('username');
//Encrypted password
$password = md5($this->input->post('password'));
//login user
$user_id = $this->user_model->login($username, $password);
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata('user_data',$user_data);
// Set message to be sent
$this->session->set_flashdata('user_login', 'Welcome');
redirect('posts');
} else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
}
public function get_user()
{
if($this->session->userdata('logged_in')){
$username = $this->session->userdata('username');
$data['results'] = $this->user_model->get_user($username);
$this->load->view('templates/header');
$this->load->view('users/login', $data);
$this->load->view('templates/footer');
}
}
There is basic problem in your Controller
Session Data Problem: In your Controller you storing all array data in CodeIgniter Session:
the 'user_data' would work like array key, and all other array will be assign as keys data;
$this->session->set_userdata('user_data', $user_data);
and you retrieving/checking the session data by using $this->session->userdata('logged_in') and $this->session->userdata('username'), It's wrong my friend. You can get user data session by $this->session->userdata('user_data')['username'] or $this->session->userdata['user_data']['username'] ...
Because the session would be like;
Array
(
[__ci_last_regenerate] => 1499791562
// This is the array key 'user_data' where your array data stores
[user_data] => Array
(
[user_id] => 1
[username] => scott
[email] => scott.dimon#example.com
[phone_number] => 1234567890
[first_name] => Scott
[logged_in] => 1
)
)
So, you have to have use 'user_data' with session to get your data
One thing I would like to share with everyone, Always Read The Docs and manual Carefully. Believe me if you read before the start, your code would be more nicer and cleaner... Ha ha ha ha ha.. ;) :|
When you login if you set the users_id in session you can get the information like
Read manual also
https://www.codeigniter.com/user_guide/database/results.html#result-rows
https://www.codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
Make sure you autoload session, and database.
Examples ONLY below.
Filename: User_model.php
class User_model extends CI_Model {
public function get_user($id)
{
$this->db->where('user_id', $id);
$user_query = $this->db->get('yourtable');
return $user_query->row_array();
}
}
Filename: Dashboard.php
Controller
<?php
class Dashboard extends CI_Controller {
public function __construct()
{
parent::__construct();
if (!$this->session->userdata('user_id'))
{
redirect('logoutcontroller');
}
$this->load->model('user_model');
}
public function index()
{
$userdata = $this->user_model->get_user($this->session->userdata('user_id'));
/** You can use what you want example
$data['email'] = $userdata['email'];
**/
$data['username'] = $userdata['username'];
$this->load->view('some_view', $data);
}
}
View
<?php echo $username;?>
You can use session to carry the logged in user detail.
This is your model code:
//In your model
$query = $this->db
->select('id,email,phone')
->where(['username' => $username, 'password' => $password])
->where('status','1')
->get('users');
$user_data = $query->row_array();
if (!empty($user_data)) {
return $user_data;
} else {
return FALSE;
}
In side the controller where you get the user data if username & password is correct. Here you can put the user data on session:
//In Side Controller
$user_data = $this->user_model->login($username, $password);
if(isset($user_data) && !empty($user_data)){
// you can directly add the `$user_data` to the session as given billow.
// set user data in session
$this->session->set_userdata('user_data', $user_data);
Now after putting a data on session you can retrive it any where, on any view or in side morel, controller.
//retrive the user data in any view
//To echo in view Inside your view code.
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<?= $user_phone ?> OR <?php echo $user_phone; ?>
<?= $user_email ?> OR <?php echo $user_email; ?>
On Your $this->load->view('users/login', $data); this view. Where the HTML & PHP code placed.
Example:
<html>
// Your View Page
</body>
<?php
$session_data = $this->session->userdata('user_data');
$user_email = $session_data['email'];
$user_phone = $session_data['phone'];
$user_id = $session_data['id'];
?>
<h1> Logged In User Email: <?= $user_email ?> </h1>
<h1> Logged In User Phone: <?= $user_phone ?> </h1>
<body>
</html>
Note: Once You save the user data inside the session then you don't need to pass that data to the view form controller. You just need to echo it where you need that.
You need to load session library first. like
$this->load->library('session');
Then after you can save your data into session like,
$newdata = array(
'username' => 'johndoe',
'email' => 'johndoe#some-site.com',
'logged_in' => TRUE
);
$this->session->set_userdata($newdata);
Then where ever you require at controller you can retrive session data like,
$data['session_data'] = $this->session->all_userdata();
and then pass to your view,
$this->load->view('data', $data);
and then access that data into your view with the key,
<?= $session_data['username']; ?>
I hope it helps,
Does this answer your question?
public function login($username, $password){
$db = $this->db;
//validation
$db->select('id, email, username');
$db->where('username', $username);
$db->where('password', $password);
$db->where('status', 1);
$result = $db->get('users')->row_array();
return empty($result['id']) ? false : $result['id'];
}
With a unique index on username you won't need to check the number of rows as it will be limited to 1.
if($user_id){
//creating session
$user_data = array(
'user_id' => $user_id,
'username' => $username,
'logged_in' => TRUE,
);
$this->session->set_userdata($user_data);
// Set message to be sent
$data['session_data'] = $this->session->all_userdata();
$this->session->set_flashdata('user_login', 'Welcome');
$this->load->view('posts', $data);
//redirect('posts');
}
else {
// Set message to be sent
$this->session->set_flashdata('login_fail', 'Login Failed');
redirect('users/login');
}
}
at the view,
<?php print_r($session_data); ?>
if you get your session data into print,
you can display it like,
<?= $session_data['user_id']; ?>
****Modal**
//user login**
function userlogin($data)
{
$condition = "username =" . "'" . $data['username'] . "' AND " . "password =" . "'" . $data['password'] . "' AND " . "status = '1'";
$this->db->select("*");
$this->db->from("user");
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1)
{
return $query->result();
}
else {
return false;
}
}
And in your Controller check
if($this->modal_name->login()==false)
{
//redirect user to login page
}
else
{
$data['details'] = $this->modal_name->login();
$this->load->view("post",$data);
}
View
foreach($details as $detail)
{
echo $detail->id;
echo $detail->username;
}

Learning php - How to query the database from logged_in.php?

Im trying to learn php and have set up a login system using php-login.net (advanced script). The script uses an index.php file to check if the user is logged in (via login.php)
Within login.php, the script uses a function "databaseConnection" to connect to the database as
$this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname='. DB_NAME . ';charset=utf8', DB_USER, DB_PASS);
An example query is executed as:
$query = $this->db_connection->prepare('UPDATE users SET username = :user_name WHERE user_id = 1');
$query ->bindValue(':user_name ', $user_name , PDO::PARAM_STR);
$query ->execute();
if ($query_update->rowCount() == 0) {
// Something here
} else {
// Something else here
}
index.php checks if the user is logged in and if logged in, loads logged_in.php
My question is: How do I select something from the database within logged_in.php. Should i create a new db connection? If so how. I cannot reference $this->db_connection->prepare within logged_in.php
Also, what's a good source to learn step by step. I tried http://php.net/manual/ but that isnt making sense to me.
Thank you!
use php frameworks. so that it is fast and easy. Here login controller ive used in codeigniter framework
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('login_model', 'lm');
$this->load->model('posts_model', 'pm');
date_default_timezone_set('Asia/Hong_Kong');
}
//check password in the database
public function check_database($password){
$username = $this->input->post('username');
$result = $this->lm->login($username, $password);
if($result){
$sess_array = array();
foreach($result as $row){
$sess_array = array(
'id'=>$row->user_id,
'username'=>$row->username,
);
$this->session->set_userdata('loggedIn', $sess_array);
}
return true;
}else{
$this->form_validation->set_message('check_database', 'Invalid Username or Password.');
return false;
}
}
public function auth(){
$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_check_database');
if($this->form_validation->run() == FALSE){
$this->index();
}else{
redirect('post');
}
}
public function index(){
$data['title'] = "Login here | OkDito.ph Cebu's # 1 Buy and Sell Website";
$data['great_deals'] = $this->pm->greatdeals();//get all items
$data['getAllPendingPosts'] = $this->pm->getAllPendingPosts();
$tmp_pending = array();
$tmp_pending = $data['getAllPendingPosts'];
if(!empty($tmp_pending )){
$pending = 1;
}
else{
$pending = 0;
}
$data['pending'] = $pending;
if($this->session->userdata('loggedIn')){
$login = $this->session->userdata('loggedIn');
if(!empty($login)){
redirect('post');
}
}
else{
$this->template_lib->set_view('index_view', 'login_view', $data,'',$data);
}
}
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
* User library for the Model..all commonly used functions should be placed here
* #author: team gabayan
* #created: 7/1/11
*/
class Login_model extends CI_Model{
//check if email exist in the database
public function email($email){
$this->db->select(
'tbl_users.email'
)
->from('tbl_users')
->where('email', $email);
$q = $this->db->get();
if($q->num_rows() == 1){
return $q->result();
}else{
return false;
}
}
Here. Hope this helps
public function login($username, $password){
$sha_password = sha1($password);
$this->db->select(
'tbl_users.user_id,
tbl_users.username,
tbl_users.password,
tbl_users.status
'
)
->from('tbl_users')
->where('tbl_users.username', $username)
->where('tbl_users.password', $sha_password);
$query = $this->db->get();
if($query->num_rows() == 1){
return $query->result();
}else{
return false;
}
}
}//endclass
/End of File Login_model.php/
/File Location: ./application/models/login_model.php/

Codeigniter - sessions not working through controller and view

I'm trying to make a login using sessions in codeigniter at the time the username and password match, but I can't get it. I'm doing this:
Controller:
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
...code when username and password match:
if($pass === $user){
$this->session->set_userdata(array(
'user_id' => $login['id_user'],
));//we create the session 'user_id'
}
here it is supposed that we created a session called 'user_id'
in the view it doesn't work, I have this:
if( !$this->session->userdata('id_user') ){
//see this content
//first content
}else{
//see this other
//second content
}
but I always see the same content('second content').
trying to destroy it (but not working):
public function logout()
{
//session_unset();
// destroy the session
//session_destroy();
$this->session->unset_userdata('id_user');
header("Location: ".base_url() );
}
what am I doing wrong? thanks
EDIT1:
$password = md5( $this->input->post('inputpassword') );
$login = $this->login_select->get_username($username);
//si no coincide
if( $login['password'] !== $password ) {}
Note : Always use database to handle user logins. (Code is related to database login check)
in your database create table with user and add this 2 fields.
username
password
Add some user logins to it
Then in your code
public function __construct()
{
parent::__construct();
$this->load->model('main_select');
$this->load->helper('url');
$this->load->library('session');
}
// logging
public function loging()
{
$user = mysql_real_escape_string($_POST['username']);
$pass = md5(mysql_real_escape_string($_POST['password']));
$validate = $this->main_select->validate_user($user,$pass);
if(empty($validate) || $validate>1)
{
//Not a valid user
//redirect to login page
$this->load->view('loging');
}
else
{
//valid user
//set the session
$array = array('user_id' => '$user');
$this->session->set_userdata();
//redirect to normal page
$this->load->view('home_page');
}
}
//logout
public function logout()
{
$result= $this->session->sess_destroy();
if ((isset($result)))
{
header("Location: ".base_url() );
}
else
{
}
}
In Model
public function validate_user($user,$pass)
{
$query = $this->db->query("SELECT * FROM user WHERE username= '$user' AND password='$pass'");
$result = $query->result_array();
$count = count($result);
return $count;
}
modify this line of changes then your script will work as id_user need to set first to use in script.
if($pass === $login['password'] && $user===$login['username']){
$this->session->set_userdata(array(
'id_user' => $login['id_user'],
));//we create the session 'user_id'
}
here $login['password'] and $login['username'] are data come from tables and need to change fieldname pass or user according to your user table.

How to Update Data in CodeIgniter?

First, sorry for my bad english, if you don't understand what I'm saying, you can ask for it and I will search for another suitable and precise words.
Now, I've been working with codeigniter in this last 2 weeks, so I got so many question for it, but I found 1 which is hanging on my mind.
I started with simple CRUD, then make it advanced, it's good so far, until I got stuck while updating data. When I click the "submit" button, I get only 404 page. And when I see the database, nothing change.
Here's the controller's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Master_user extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('mod_master_user');
$this->load->library('datatables');
}
public function index(){
if ($this->session->userdata('type') == 'admin') {
$data['hasil'] = $this->mod_master_user->getall();
$datum['content'] = $this->load>view('master_user/view',$data,true);
$this->load->view('main',$datum);
} else if ($this->session->userdata('type') == 'user'){
$a= $this->load->model('m_absensi');
$aa["content"] = $this->load->view('absensi/form',$a,true);
$this->load->view("absensi/mainUser",$aa);
}
}
public function tambah_data(){
if($this->input->post('nama')){
$this->mod_master_user->tambah();
redirect('master_user');
}else{
$this->load->view('master_user/add');
}
}
public function update_data($id_user)**//i use this method for updating data**{
if($this->input->post('submit')){
$this->mod_master_user->update($id_user);
redirect('master_user/index');
}
$data['hasil']=$this->mod_master_user->getById($id_user);
$this->load->view('master_user/edit',$data);
}
public function delete_data($id_user){
$this->mod_master_user->delete($id_user);
redirect('master_user');
}
public function error()
{
$this->output->set_status_header('404');
$data['content'] = '404';
$this->load->view('master_user/404',$data);
}
public function print_report()
{
$this->load->view('master_user/print');
}
public function jam_masuk()
{
$this->load->view('master_user/jam_masuk');
}
}
Here comes the model's code:
<?php if(!defined('BASEPATH')) exit('No direct script access allowed');
Class Mod_master_user extends CI_Model{
var $tabel_name = 'master_user';
function __construct() {
parent::__construct();
}
public function getall(){
$ambil_data = $this->db->get('master_user');//mengambil tabel master_user
if ($ambil_data->num_rows() > 0 ){ //jika data lebih dari 0
foreach ($ambil_data->result() as $data){
$hasil[] = $data;
}
return $hasil;
}
}
public function tambah(){
$id_user = $this->input->post('id_user');
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$tanggal_lahir = $this->input->post('tanggal_lahir');
$tempat_lahir = $this->input->post('tempat_lahir');
$role = $this->input->post('role');
$data = array (
'id_user'=> $id_user,
'nama'=>$nama,
'password'=>md5($password),
'tanggal_lahir'=>date('Y-m-d',strtotime($tanggal_lahir)),
'tempat_lahir'=>$tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->insert('master_user', $data);
}
public function update($id_user)**//i use this method to updating data**{
$id_user=$this->input->post('id_user');
$nama=$this->input->post('nama');
$password=$this->input->post('password');
$tanggal_lahir=$this->input->post('tanggal_lahir');
$tempat_lahir=$this->input->post('tempat_lahir');
$role=$this->input->post('role');
$data = array (
'id_user' => $id_user,
'nama' => $nama,
'password'=> $password,
'tanggal_lahir'=> $tanggal_lahir,
'tempat_lahir'=> $tempat_lahir,
'role'=>$role
);
$this->db->where('id_user',$id_user);
$this->db->update('master_user',$data); //update data
}
public function getById($id_user){ //mengambil data dari db berdasarkan id (primary key)
return $this->db->get_where('master_user',array('id_user'=>$id_user))->row();
}
public function delete($id_user){
$this->db->where('id_user',$id_user);
$this->db->delete('master_user'); //query delete data
}
public function cek_user_login($username, $password) {
$this->db->select('*');
$this->db->where('NAMA', $username);
$this->db->where('PASSWORD', md5($password));
$query = $this->db->get($this->tabel_name, 1);
if ($query->num_rows() == 1) {
$this->db->limit(1);
return $query->row_array();
}
}
public function validasi()
{
$nama = $this->input->post('nama');
$password = $this->input->post('password');
$check = $this->mod_master_user->check($nama, md5($password));
if($check->num_rows() > 0)
{
//login berhasil, buat session
//$this->session->set_userdata('username',$username);
redirect('master_user');
}
else
{
//login gagal
//$this->session->set_flashdata('message','Username atau password salah');
redirect('users');
}
}
}
So far, I get no answer on other forums, so I asked for the answer here :)
Any answer/help will be appreciated. Thank you :)
It's been some time since I used CodeIgniter.
Are you loading the input class? so you can actually receive $_GET and $_POST data? I think it does this by default actually.
This might be a bit too simple, but are you calling the right URI and are you sure its reaching your view??
Might help to see your view, are you using the form helper for this? https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html
If you get 404, then the problem is in your form action tag. It means it doesn't post to the right url.
This is most likely (if not surely) due to a bad route.
In config/routes.php, you need a route like: $route['master_user/update/(:any)'] = 'master_user/update_data/$1;
And in your view you would need a form with the action pointing to that route, such as:
<form action="master_user/update_data/1">
<!-- your fields and submit button -->
</form>
Where the number 1 (in the action url) is the id of the register being updated.

CodeIgniter: Not showing login error message

Could you please help me work out why my code will not show the setmessage:
$this->form_validation->set_message('Sorry %s is not correct.');
The validation is happily showing that they are required:
home.php -> controller
<?php
ob_start();
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
function __construct(){
parent::__construct();
}
function index(){
$this->login();
}
public function login()
{
//Loads The Page Template
$this->template->set('title','Admin Login');
//Validation Check
$this->form_validation->set_rules('username','Username','required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password','Password','required|trim|max_length[200]|xss_clean|callback_checkUsernamePassword');
if($this->form_validation->run() == FALSE){
$this->template->load('template','admin/admin_login');
}else{
extract($_POST); // Gets data from form and creates vars
$user_id = $this->login_model->check_login($username,$password);
if(! $user_id || $password){ // != If username or password are not correct
$this->session->set_flashdata('login_error',TRUE); //does not add the non valid login to the session
$this->form_validation->set_message('Sorry %s is not correct.');
redirect('admin');
}else{
$this->session->set_userdata('logged_in',TRUE);
$this->session->set_userdata('user_id',$user_id);
redirect('admin/dashboard');
}
}
}
function logout(){
$this->session->unset_userdata('logged_in');
echo 'You have now been logged out';
redirect('admin');
}
}
//End of file home.php
//Location: ./application/controllers/admin/home.php
login_model.php -> model
<?php
class Login_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
function Login_model(){
parent::Model();
}
function check_login($username,$password){
$MD5_password = md5($password); // Tells the db that the password is a MD5 #
$query_str ="SELECT id FROM users WHERE email = ? and password = ?"; // Tells the db that this is a query
$result = $this->db->query($query_str, array($username, $MD5_password)); // Result
//If it is all correct
if($result->num_rows() == 1){
return $result->row(0)->id;
}else{
return false;
}
}
}
?>
I have tried the following:
$lang['error'] = "Sorry your %s is incorrect.";
- This is set in the lang file
and
$this->form_validation->set_message('error','Sorry %s is not correct.');
I am unsure what the 2nd para must be
Your really really really should read the user_guide. Your logic is incorrect. For example, you didn't use your callback. That's why your error messages don't show. I have put in a few comments for you to read.
public function login()
{
$this->template->set('title','Admin Login');
$this->form_validation->set_rules('username','Username', 'required|trim|max_length[50]|xss_clean');
// You aren't using the callback here.
$this->form_validation->set_rules('password','Password', 'required|trim|max_length[200]|xss_clean|callback_checkUsernamePassword');
if($this->form_validation->run() == FALSE){
$this->template->load('template','admin/admin_login');
}else{
// You shouldn't be adding messages when the validation has already passed. The setting should be when the validation is false.
extract($_POST);
$user_id = $this->login_model->check_login($username,$password);
if(! $user_id || $password){
$this->session->set_flashdata('login_error',TRUE); //does not add the non valid login to the session
$this->form_validation->set_message('Sorry %s is not correct.');
redirect('admin');
}else{
$this->session->set_userdata('logged_in',TRUE);
$this->session->set_userdata('user_id',$user_id);
redirect('admin/dashboard');
}
}
}
Here's what you should do. I'm not going to code everything but will give you an idea.
public function login()
{
$this->template->set('title','Admin Login');
$this->form_validation->set_rules('username','Username', 'required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password','Password', 'required|trim|max_length[200]|xss_clean|callback_checkUsernamePassword');
if($this->form_validation->run() == TRUE){
$this->session->set_userdata('logged_in',TRUE);
$this->session->set_userdata('user_id',$user_id);
redirect('admin/dashboard');
}
$this->template->load('template','admin/admin_login');
}
public function checkUsernamePassword() {
extract($_POST); // Gets data from form and creates vars
$user_id = $this->login_model->check_login($username,$password);
if(! $user_id || $password){ // != If username or password are not correct
$this->session->set_flashdata('login_error',TRUE); //does not add the non valid login to the session
$this->form_validation->set_message('checkUsernamePassword', 'Sorry %s is not correct.');
return FALSE
}else{
$this->session->set_userdata('logged_in',TRUE);
$this->session->set_userdata('user_id',$user_id);
redirect('admin/dashboard');
}
}
The set_message function for CodeIgniter's Form Validation class takes two parameters - the first being the name of the validation rule you would like to modify the message for, and the second being the modified message itself.
http://codeigniter.com/user_guide/libraries/form_validation.html
So if you would like to modify the message for the required fields, you would use:
$this->form_validation->set_message('required', 'Sorry %s is not correct.');
$this->form_validation->set_message();
This is used when you are trying to make your own Validation Functions or setting new error messages
If you are trying to make your own validation function then you should follow below article
http://codeigniter.com/user_guide/libraries/form_validation.html
What you can do is according to the returned value you can set the $this->session->set_flashdata(); and show it on the admin page.
http://codeigniter.com/user_guide/libraries/sessions.html

Categories