How to check if email already exists in db with CodeIgniter - php

I am doing application in CodeIgniter. I don't know how to compare email against db in CodeIgniter, please any one, help me.
Controller
public function signup()
{
$this->load->view('signup');
}
public function savedata(){
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'firstname', 'required');
$this->form_validation->set_rules('lastname', 'lastname', 'required');
if ($this->form_validation->run() == TRUE) // Only add new option if it is unique
{
$result = $this->account_model->insert();
if($result > 0)
{
$data['message'] = "Added successfully";
$this->load->view('signup',$data);
}
else
{
$this->index();
}
}
else
{
$this->load->view('signup');
}
}
How to check whether email already exists or not?

Suppose, you have user table and email column. So you have to add this line in form validation
$this->form_validation->set_rules('email','Email','required|valid_email|is_unique[users.email]');
Note
And need an unique index in your email column
check Documentation

Add a rule:
$this->form_validation->set_rules('email', 'Email', 'callback_rolekey_exists');
In the same Controller:
function rolekey_exists($key) {
$this->roles_model->mail_exists($key);
}
In Model,
function mail_exists($key)
{
$this->db->where('email',$key);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
Reference

Best Way
$this->form_validation->set_rules(
'email', 'Email', 'valid_email|required|is_unique[usr_user.user_email]',
array('is_unique' => 'This %s already exists.')
);

//in controller
public function usernameExist($username)
{
$user = $this->Model-> usernameExist($username);
if ($user) {
$this->form_validation->set_message(
'usernameExist',
'Username is already exist.'
);
return false;
} else {
return true;
}
}

function username_Exist($key)
{
$this->db->where('username', $key);
$query = $this->db->get('signup');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
//type this in model

$this->form_validation->set_rules('username', 'User', 'trim|required|callback_username_Exist');
//type in controller in form validation

Related

User login status activation check in codeigniter?

I'm new in Codeigniter. I have a login system where user with status is 0 can't do login yet and where user with status 1 can login. I might be have a mistake in my code. So, i hope you can find where is my mistake and help me to make it right. here's my code.
My Controller
public function login() {
$this->form_validation->set_rules('no', 'No', 'required|min_length[10]|max_length[16]|integer');
$this->form_validation->set_rules('password', 'password', 'required|md5|xss_clean');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if($this->form_validation->run()== FALSE) {
$this->load->view('v_login');
}else{
$no = $this->input->post('no');
$password = $this->input->post('password');
$cek = $this->m_user->ambilPengguna($no, $password);
$status = $this->m_user->ambilStatus($no); //HERE'S THE PROBLEM
if($cek->num_rows()<> 0 && $status == '1') { //HERE'S TOO, IT WON'T CHECK THE STATUS.
$this->session->set_userdata('isLogin', TRUE);
$this->session->set_userdata('data_user',$cek->row());
redirect('c_belajar');
}else {
echo " <script>
alert('Login failed! call the administrator to activate your account');
history.go(-1);
</script>";
}
}
}
My Model
public function ambilPengguna($no, $password) {
$this->db->select('*');
$this->db->from('tb_user');
$this->db->where('no_id', $no);
$this->db->where('password', $password);
$query = $this->db->get();
return $query;
}
public function ambilStatus($no){
$this->db->select('status');
$this->db->from('tb_user');
$this->db->where('no_id', $no);
$query = $this->db->get();
return $query;
}
There's a mistake on controller. Please help me.
Alright! May I suggest a little code restructure
Controller
class YourController extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model('login_model');
$this->load->library('form_validation');
}
public function login()
{
if($_POST)
{
$config=array(
array(
'field' => 'no',
'label' => 'Number',
'rules' => 'trim|required',
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required',
)
);
$this->form_validation->set_rules($config);
if($this->form_validation->run()==false)
{
$data['errors']=validation_errors();
$this->load->view('login',$data);
}
else
{
$check=$this->login_model->checkUser($_POST); // you can use xss clean here filter post data
if(!$check)
{
$data['errors']='Invalid Password';
$this->load->view('login',$data);
}
elseif($check==1)
{
$data['errors']='Your account status is not active yet, Please contact Administrator';
$this->load->view('login',$data);
}
else
{
$this->session->set_uerdata($check);
redirect(base_url().'dashboard');
}
}
}
else
{
$this->load->view('login');
}
}
}
Model
class login_model extends CI_Model {
function __construct()
{
parent::__construct();
}
public function checkUser($data)
{
$st=$this->db->select('*')
->from('tbl_user')
->Where('no_id', $data['no'])
->where('password', $data['password'])
->get()->result_array();// you can use row()
if(count($st)>0)
{
if($st[0]['status']==0){
return 1;
}
else
{
return $st[0];
}
}
else
{
return false;
}
}
}
Try this, this working in my project..
Your Model
public function ambilStatus(){
$this->db->where('no_id', $this->input->post('your input name'));
$query = $this->db->get($this->db->dbprefix . 'tb_user');
$ret = $query->row();
return $ret->account_status;
}
And Your Controller
$status = $this->m_user->ambilStatus();
if($status && $cek->num_rows() == 1 ) {

how to use callback in codeigniter

I'm using codeigniter and I want to create validation for name field if the name exists in my table. ut I'm getting blank screen, can everyone help me?
this is my controller:
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
}
public function isNameExist($name) {
$this->load->library('form_validation');
$is_exist = $this->cabang_model->isNameExist($name);
if ($is_exist) {
$this->form_validation->set_message('isNameExist', 'Name is already exist.');
return false;
} else {
return true;
}
}
and this is my model
public function isNameExist($name) {
$this->db->select('nama_cabang');
$this->db->where('nama_cabang', $name);
$query = $this->db->get('master_cabang');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
After submit I get the blank screen.
Thanks,
Martin
You can simply use is_unique to perform this action instead of using callback.
Your syntax will be
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|is_unique[master_cabang.nama_cabang]');
The problem is on your insertCabang() controller function. You run the
validation, but what should it do after? You must echo the result, or load some view.
public function insertCabang(){
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'nama_cabang', 'trim|required|callback_isNameExist');
if($this->form_validation->run()){
echo 'validated ok';
}else{echo validation_errors();}
}

Codeigniter user access level

Model:
Class User extends CI_Controller
{
function login($username, $password)
{
$this->db->select('id', 'username', 'password', 'access');
$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;
}
}
}
Controller:
class VerifyLogin extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->model('user','',TRUE);
}
function index()
{
$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)
{
//Field validation failed. User redirected to login page
$this->load->view('login_view');
}
else
{
//Go to private area
redirect('home', 'refresh');
}
}
function check_database($password)
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
//query the database
$result = $this->user->login($username, $password);
if($result)
{
$sess_array = array();
foreach($result as $row)
{
$sess_array = array(
'id' => $row->id,
'username' => #$row->username
);
$this->session->set_userdata('logged_in', $sess_array);
}
return TRUE;
}
else
{
$this->form_validation->set_message('check_database', 'Invalid username or password');
return false;
}
}
}
How to deal with access? In the database is int number, you need to make a selection from the base, to get the numbers from the table and access to work with him. How to implement it?

Object not found on codeigniter

I have codeigniter installed on my localhost
The main.php controller is
class Main extends CI_Controller {
public function index()
{
$this -> login();
}
public function login()
{
$this->load->view('login');
}
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if($this->form_validation->run())
{
redirect('main/members');
}
else
{
$this->load->view('login');
}
}
}
The login is working page is coming,but after I fill the username and password,should take me to login/main/login_validation and from there the function login_validation() should either redirect to main/members or show me the login page.But what happens is when I submit the form,the object not found error is coming.Can anyone help me out?
form is
form_open('main/login_validation');
To answer what I think your question is getting at, you're using the form_validation class wrong. You should be testing whether or not the form_validation->run() is TRUE (all fields passed validation) or FALSE (there was an error in one or more of the inputs). Structure you code like such:
public function login_validation() {
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email','required');
$this->form_validation->set_rules('password','Password','required|md5');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('login');
}
else
{
redirect('main/members');
}
}
This is covered in the CodeIgniter documentation here.
in your controller ..you could try this..
function index()
{
//This method will have the credentials validation
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
if($this->form_validation->run() == FALSE)
{
//Field validation failed. User redirected to login page
$this->load->view('login');
}
else
{
$this->check_database();
//redirect('home');
}
}
function check_database()
{
//Field validation succeeded. Validate against database
$username = $this->input->post('username');
$password = $this->input->post('password');
//query the database
$query_result = $this->model_login->login($username, $password);
if($query_result)
{
$this->load->view('main/members');
}
else
{
redirect('login');
}
}
in model
function login($username,$password){
$query = $this->db->query("SELECT * FROM `login` WHERE `username`= '".$username."' AND
password='".$password."' LIMIT 1");
if ($query->num_rows() > 0)
return TRUE;
else
return FALSE;
}

To retrieve the forgot password

In the below code i have used codeigniter code i enter username and password to db.but i want to retrieve my forgot password .I tried but i got the following errors pls help to recify the issue.
Controller:
<?php
class Login extends CI_Controller {
function index()
{
$data['main_content'] = 'login_form';
$this->load->view('includes/template', $data);
}
function validate_credentials()
{
$this->load->model('membership_model');
$query = $this->membership_model->validate();
if($query) // if the user's credentials validated...
{
$data = array(
'username' => $this->input->post('username'),
'is_logged_in' => true
);
$this->session->set_userdata($data);
redirect('site1/members_area');
}
else // incorrect username or password
{
$this->index();
}
}
function signup()
{
$data['main_content'] = 'signup_form';
$this->load->view('includes/template', $data);
}
function create_member()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('first_name', 'Name', 'trim|required');
$this->form_validation->set_rules('last_name', 'Last Name', 'trim|required');
$this->form_validation->set_rules('email_address', 'Email Address', 'trim|required|valid_email');
$this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[4]');
$this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('password2', 'Password Confirmation', 'trim|required|matches[password]');
$this->load->helper('date');
if($this->form_validation->run() == FALSE)
{
$this->load->view('signup_form');
}
else
{
$this->load->model('membership_model');
if($query = $this->membership_model->create_member())
{
$data['main_content'] = 'signup_successful';
$this->load->view('includes/template', $data);
}
else
{
$this->load->view('signup_form');
}
}
}
public function forgot_password()
{
$this->form_validation->set_rules('email_address','Email Address','trim|required|valid_email|callback__check_email_exists');
if($this->form_validation->run() == FALSE)
{
// VALIDATION ERRORS, SHOW VIEWS
$this->index();
}
else
{
// ALL IS GOOD, UPDATE EMAIL, AND REDIRECT TO CURRENT URL
$this->load->view('login_form');
}
}
public function _check_email_exists($email)
{
// LOAD AND USE YOUR MODEL TO CHECK EMAIL EXISTS HERE
if ( ! $email_exists )
{
$this->form_validation->set_message('email_address', 'That email address don\'t exist, sucka!');
return FALSE;
}
else
{
return TRUE;
}
}
function logout()
{
$this->session->sess_destroy();
$this->index();
}
}
model
<?php
class Membership_model extends CI_Model {
function validate()
{
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', md5($this->input->post('password')));
$query = $this->db->get('membership');
if($query->num_rows == 1)
{
return true;
}
}
function create_member()
{
$new_member_insert_data = array(
'first_name' => $this->input->post('first_name'),
'last_name' => $this->input->post('last_name'),
'email_address' => $this->input->post('email_address'),
'username' => $this->input->post('username'),
'date' => date('Y-m-d H:i:s', now()),
'password' => md5($this->input->post('password'))
);
$insert = $this->db->insert('membership', $new_member_insert_data);
if ($this->db->_error_number() == 1062)
{
echo"<script>alert('This value already exists');</script>";
}
if ($this->db->_error_number() == "")
{
$this->session->set_flashdata('create', 'create');
}
return $insert;
}
public function val_forgot_password()
{
$this->db->where('email_address', $this->input->post('email_address'));
$query = $this->db->get($this->members);
if($query->num_rows == 1)
{
return true;
}
else
{
return false;
}
}
function curdate() {
// gets current timestamp
date_default_timezone_set('Asia/Manila'); // What timezone you want to be the default value for your current date.
return date('Y-m-d H:i:s');
}
}
view:login_form
<?php $this->load->view('includes/header'); ?>
<link rel="stylesheet" type="text/css" href="<?php echo base_url();?>css/style1.css" />
<div id="login_form">
<h1>Login!</h1>
<?php
echo form_open('login/validate_credentials');
echo form_input('username', 'Username');
echo form_password('password', 'Password');
echo form_submit('submit', 'Login');
echo anchor('login/signup', 'Create Account');
echo form_close();
?>
</div><!-- end login_form-->
<?php $this->load->view('includes/footer'); ?>
<?php
echo form_open('login/forgot_password');
echo "Email Address: " . form_input('email_address', set_value('email_address', ''));
echo br(2);
echo form_submit('submit','Send Email');
echo form_close();
echo br(1);
echo validation_errors('<p>Error: ');
?>
Well first of all you will need a function in the controller to bring the user to a forgot user page.
public function forgot_pass(){
$this->load->view('forgot_pass_view');
}
Then you will probably need to ask atleast for the email address in the view.
Create another function to verify the email address in the controller, and if it matches send a mail with a new temporary password.
public function check_email(){
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'email_check', 'callback_email_check');
if ($this->form_validation->run() == FALSE){
//throw error
} else {
//send email
}
}
public function email_check(){
//use this function to check if the email exists and return false if it is not the DB
}

Categories