Codeigniter Check For Duplicate on Edit Function - php

Check For Duplicate on Edit Function
Currently my DB table
USERDB
userId userName userPassword userEmail userAddress userPhone
What I want
Allow to check on "userName" duplication" and if "userName" return
true , then it allow to edit other textfield.
Problem Met:
When i did not change anything on my "userName" field , and i edited
userEmail, it will always return FALSE due to my "userName" is
duplicate with current DB data.
$checkvalidation = $this->userdb->UsernameDuplicatechecking($userName);
if($checkvalidation == TRUE){
$this->userdb->updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
}else{
$this->session->set_flashdata('errormessage', 'Duplicate');
redirect("User/EditUserAccount/$id");
}
Update Model Code
public function updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
{
$UserArray = array(
'userName' => $userName,
'userEmail' => $userEmail,
'userAddress' => $userAddress,
'userPhone' => $userPhone,
);
$this->db->set($UserArray);
$this->db->where('userId',$id);
$this->db->update('USERDB');
}

Will you please share the code of function UsernameDuplicatechecking($userName) or you can try the below solution and let me know if it helps. Add below function to your userdb model
function checkDuplicateUsername($userName)
{
$this->db->where('userName',$userName);
$query = $this->db->get('USERDB');
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
Now update your controller function as below:
$checkvalidation = $this->userdb->checkDuplicateUsername($userName);
if($checkvalidation == true){
$this->userdb->updateUser($userName,$userEmail,$userAddress,$userPhone,$id);
}else{
$this->session->set_flashdata('errormessage', 'Your message here');
redirect("User/EditUserAccount/$id");
}

Consider you have the username input named userName, one solution is you could add a conditional is_unique validation, so that if user doesn't change his/her username then don't validate it as unique.
This could be done by pulling user's userName from database by id and compare it with the posted userName value :
$id = $this->input->post('id');
$old_username = $this->db->get_where('USERDB', array('userId' => $id))->row_array();
$original_value = $old_username['userName'];
if($this->input->post('userName') != $original_value) {
$is_unique = '|is_unique[USERDB.userName]'
} else {
$is_unique = ''
}
$this->form_validation->set_rules('userName', 'User Name', 'required|trim|xss_clean'.$is_unique);

Instead of checking if ($query == true).Check if ($validation == true) and your else condition is wrong as if username is duplicate it will go in the if condition.

Related

How can I display the name of my admin full name after login - Codeigniter

I am having a trouble on displaying my admin's full name, like for example admin full name is John Doe, it is not displaying. I am still learning codeigniter please give me advice thank you!
here is my controller
//Get username
$username = $this->input->post('username');
//Get and encrypt the password
$password = $this->input->post('password');
// Login user
$user_id = $this->role_model->login($username, $password);
if ($user_id) {
// Create session
$user_data = array(
'user_id' => $user_id,
'name' => $user_id->name,
'username' => $username,
'logged_in' => true
);
$this->session->set_userdata($user_data);
//Set message
$this->session->set_flashdata('user_loggedin','You are now logged in');
redirect('pages/index');
here is my View - where I would like to display my full name, as you can see 'name' is the data field I have to display but it is does not show anything, it gives an error that says name is not defined.
<li><a> Welcome, <?php echo $this->session->name ?> </a></li>
Model
public function login($username, $password){
//Validate
$this->db->where('username',$username);
$this->db->where('password',$password);
$result = $this->db->get('users');
if ($result->num_rows() == 1) {
return $result->row(0)->id;
}else{
return false;
}
}
Your method login() returns only id = digit (return $result->row(0)->id;), not object (in controller your get $user_id->name).
Do this, in the model:
if ($result->num_rows() == 1) {
return $result->row(0); // fix
}else{
return false;
}
In the controller:
$user = $this->role_model->login($username, $password);
$user_data = array(
'user_id' => $user->id, // fix
'name' => $user->name, // fix
'username' => $username,
'logged_in' => true
);
It shows undefined because it is indeed undefined.
In your view your're trying to echo the returning value of a function called userdata(), does that function actually exist? Or is $this->session->userdata an array? in which that case, you need to use [ index ] to acces a member within an array. i.e. $this->session->userdata['name'], but also, that member needs to exist first.
controller :
if($this->Login_model->login_valid($email,$password))
{
$sessiondata = array(
'username' => $email
);
$this->session->set_userdata('logged_in', $sessiondata);
redirect('narson');
}
else
{
$this->session->set_flashdata('error',"Invalid Username And password");
redirect('login');
}
model:
public function login_valid($username,$password)
{
$this->db->where('username',$username);
$this->db->where('password',$password);
$query = $this->db->get('admin');
if($query->num_rows() > 0)
{
return true;
}
else
{
return false;
}
}

CodeIgniter - username and email existence check doesn't work

I'm trying to check whether or not an email or username exists in the database before inserting data into the database. For a reason I do not understand, despite using the email_exists and username_exists functions, when inserting the data, the database throws a field not unique error for username and email fields.
The username_exists and email_exists functions gets any usernames or emails where they match the username or email submitted by the form. The functions then return true if there is a username or email that exists, or false if the opposite. When both functions return false (i.e. username and email don't exist in the database) it inserts the form data into the database.
Any help would be great!
Controller Function
public function register(){
if($this->session->userdata('loggedIn') == TRUE){
$this->session->set_flashdata('error_msg', 'please log out to access this page ');
echo 'Please log out to access this page!...';
sleep(2);
redirect('index.php/user/dashboard');
}
$data['session_data'] = array(
'userID' => $this->session->userdata('userID'),
'loggedIn' => $this->session->userdata('loggedID')
);
$this->load->view('navigation');
$this->load->view('register', $data);
echo 'registration page - ';
if($this->input->post('register')){
$this->form_validation->set_rules('username', 'username', 'required');
$this->form_validation->set_rules('email', 'email', 'required|valid_email');
$this->form_validation->set_rules('password', 'password', 'required');
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
if($this->form_validation->run() == true){
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
if($username_exists == false && $email_exists == false) {
$this->user_model->add_user_account($user_details);
echo 'user added successfully: '. $user_details[0];
$this->session->set_flashdata('success_msg', 'SUCCESSFULLY ADDED USER, username and email do not already exist!... ');
sleep(2);
redirect('index.php/user/login');
} else {
echo 'username or email already exists! try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED - username or email exists!...');
sleep(2);
redirect('index.php/user/register');
}
} else {
echo 'error occured, try again!...';
$this->session->set_flashdata('error_msg', 'ERROR OCCURRED- something didn\'t work');
sleep(2);
redirect('index.php/user/register');
}
}
}
Model Functions
public function add_user_account($user_details){
$this->db->insert('user_account', $user_details);
}
public function username_exists($username){
$this->db->select('username');
$this->db->from('user_account');
$this->db->where('username', $username);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
public function email_exists($email){
$this->db->select('email');
$this->db->from('user_account');
$this->db->where('email', $email);
$query = $this->db->get();
if($query->num_rows() > 0){
return true;
} else {
return false;
}
}
$user_details[0] doesn't reference anything as you have non-numerical keys for the user_details array. I assume you mean to access the key username thus you should do $user_details['username'].
Like so:
$username_exists = $this->user_model->username_exists($user_details['username']);
$email_exists = $this->user_model->email_exists($user_details['email']);
To be honest I'm surprised this isn't giving you notice errors.
Further, you could easily make your username/email exists functions into a callback or simply use the is_unique feature of the form_validation library.
Also I'm pretty sure that you can apply strip_tags as a form_validation rule and it will remove the tags in the post variables.
Well to address your question via a means of simplification, you can use is_unique[table.field] as a validation rule.
That way you do not need to write any model methods for checking that your username or email is unique.
So in your form validation rules you can alter your username and email rules to include the is_unique rule.
$this->form_validation->set_rules('username', 'Username', 'required|is_unique[user_account.username]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[user_account.email]');
Note: The 2nd Field is the Form Label and can be anything. In this case I uppercased it. The 1st field IS case sensitive.
As to why your existing code isn't working...
Try getting friendly using var_dump(); or print_r();
i.e.
$username_exists = $this->user_model->username_exists($user_details[0]);
$email_exists = $this->user_model->email_exists($user_details[1]);
// Debug these two and see what they are...
var_dump($username_exists);
var_dump($email_exists);
Now seeing you are using an associative array in setting up
$user_details = array(
'username' => strip_tags($this->input->post('username')),
'email' => strip_tags($this->input->post('email')),
'password' => strip_tags($this->input->post('password'))
);
And then referencing them like
$username_exists = $this->user_model->username_exists($user_details[0]);
Using the above var_dump's should give you an "Aha!!!" moment.
When in doubt var_dump();

Check if data exist in database using codeigniter

I have a scenario where i have 2 tables i.e users and request and i am asking the user to fill a form, in which along with other data he has to fill email also. Now i want that if the user enters an email it should simply add the data in users table and pick the last insert id and then go ahead and save the data+last inserted id in request table and display the message
Your account is created..
Till here i have done the coding, but the part where i am stuck is
I want that if the user enters an email that is already present in users table then the code should pick the id that is present against that email and store it along with form data in the request table and display the message
"Request is submitted but you already have an account, please login to
check furthur details "
users table
id name email
1 sam sam#gmail.com
2 demo_user demo#gmail.com
request table
id email userid
1 demo#gmail 2
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
redirect('home/index');
}
}
Model
public function instant_submit()
{
$userdata = array(
'email' => $this->input->post('email')
);
$insert_data = $this->db->insert('users', $userdata);
$lastid = $this->db->insert_id();
$reqdata = array(
'email' => $this->input->post('email'),
'userid' => $lastid,
'status'=>'pending'
);
$insert_request = $this->db->insert('request', $reqdata);
return $insert_data;
}
View
<?php if($this->session->flashdata('msg')): ?>
<?php echo $this->session->flashdata('msg'); ?>
<?php endif; ?>
<?php
$reg_attributes = array('id'=>'form','role'=>"form");
echo form_open('home/submit', $reg_attributes);
?>
<?php
$data = array(
'type'=>'text',
'name'=>'email',
'placeholder'=>'Email',
'class'=>'form-control',
'id'=>'form-email'
);
echo form_input($data);
?>
<?php
$data = array(
'type'=>'submit',
'class'=>'btn-primary',
'name'=>'submit',
'content'=>'Submit!'
);
echo form_button($data);
?>
<?php echo form_close(); ?>
is_unique Returns FALSE if the form element is not unique to the table and field name in the parameter.
Syntax :
is_unique[table.field]
Example :
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.email]');
This will solve your problem
In your controller before you call this $this->user_model->instant_submit() add one more condition to check if email id already exist or not like below.
Controller
public function submit()
{
$this->form_validation->set_rules('email','Email','trim|required');
if($this->form_validation->run() == FALSE)
{
$erdata = array
(
'error' => validation_errors()
);
$this->session->set_flashdata($erdata);
redirect('home/index');
}
else
{
if(!$this->user_model->check_user_exist($this->input->post('email'))) {
if($this->user_model->instant_submit())
{
$this->session->set_flashdata('msg','Your account is created');
}
else
{
echo "failed";
}
} else {
//do whatever operation you want to do if user is already exist;
$this->session->set_flashdata('msg','Request is submitted but you already have an account, please login to check furthur details ');
}
redirect('home/index');
}
}
Now in your model create a function which can check the data of user
public function check_user_exist($email_id) {
$this->db->select('id');
$this->db->where('email',$email_id);
$query = $this->db->get('users');
$data = $query->row();
if($query->num_rows() == 1) {
return $data->id;
} else {
return false;
}
}
Note : Remember it will send false if user not found so it will create a new entry of that user.

How to take specific data from table and store it in a cookie codeigniter php?

I'm new to codeigniter and php, few days only, so I need a little help.
I'm trying to put some data in my cookie from table so I can check where to redirect user after login. In table users there are two columns named Admin and Company with one or zero if user is or not, and then i wish to insert that information to cookie.
function conformation in user_controler is:
function conformation(){
$this->load->model('user');
$q = $this->user->confr();
if($q){
$data = array(
'username' => $this->input->post('username'),
'Admin' => $this->input->post($a = $this->user->getAdmin), // get 1/0 from users column Admin
'Company' => $this->input->post($c = $this->user->getComp),
'login' => true
);
if( $a == 1 ){ //is admin redirect to admin view
$this->session->set_userdata($data);
redirect('user_controler/useradm');
}
if($c == 1){ //if company redirect to company view
$this->session->set_userdata($data);
redirect('user_controler/usercomp');
}
$this->session->set_userdata($data);// if common user redirect to user view
redirect('user_controler/userpro');
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
And in user model:
function getAdmin{
$this->db->where('Admin', 1);
$a = $this->db->get('users');
}
function getComp{
$this->db->where('Company', 1);
$a = $this->db->get('users');
}
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Also have site controller for checking login
class Site extends CI_Controller{
function __construct() {
parent::__construct();
$this->login();
}
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || login != TRUE){
$this->log;
die();
}
}
}
Of course it's not working because i should probably check these column some other way but I don't know how. I Also have enabled table ci_session and it's work perfectly without Admin and Company.
Hello and welcome to Stackoverflow.
Here are my updates to the code (I have annotated my changes):
function conformation(){
$this->load->model('user');
if($this->user->confr()){ //$q wasn't needed, as you are only using this twice
$user = $this->input->post('username'); //I have added this as I will be referring to it a couple of times.
$data = array(
'username' => $user,
'Admin' => $this->user->getAdmin($user), // Your method was questioning the original form looking for data that it would never find - This will question your model.
'Company' => $this->user->getComp($user), //Same as above
'login' => true
);
$this->session->set_userdata($data); //It doesn't matter who the user is, we shall set the data to start with.
if($this->user->getAdmin($user)){ //is admin redirect to admin view
redirect('user_controler/useradm');
}
elseif($this->user->getComp($user)){ //if company redirect to company view
redirect('user_controler/usercomp');
}
else { //Redirect non-privileged users.
redirect('user_controler/userpro');
}
}
else{ // if nothing above redirect to login page
redirect('user_controler/log');
}
}
Users Model:
function getAdmin($user){
$this->db->where('username', $user); //Before you was just returning everyone who is an admin This instead finds the user
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Admin"]==1) { return true; } //This finds if the user is a admin or not, and the function will now return a value (true)
}
}
function getComp($user) {
$this->db->where('username', $user);
$a = $this->db->get('users');
foreach($a as $u) {
if($u["Company"]==1) { return true; }
}
} //Edited similar to the function above
function conf(){
$this->db->where('username', $this->input->post('username'));
$this->db->where('password', $this->input->post('password'));
$q = $this->db->get('users');
if($q->num_rows == 1 ){
return TRUE;
}
}
Lastly your login function:
function login(){
$login = $this->session->userdata('login');
if(!isset($login) || $login != TRUE){ //You weren't referring to your $login variable
$this->log;
die();
}
}
Hopefully this helps with your problems, let me know if you need any amendments.

Can I set Ion auth to login by username OR Email

I know I can set ion auth to login by username in the config, I also know I can set it to login by email in the config.
Is there a simple way to set it it to use either automatically?
If by automatic, you mean try one and then the other to see if either gives a valid return:
The login occurs in ion_auth_model line: 899
->where($this->identity_column, $this->db->escape_str($identity))
so you could change this to do an "or" and try both columns. You would need to do this throughout the model because there is more than just the actual login to consider & there's the potential issue of a user having an email that is another user's username (however unlikely)
Its possible with only a few code rows:
Lets assume that this is your ion_auth config file:
$config['identity'] = 'username'; // A database column which is used to login with
you have to run the login function twice. If the first try (with username) didn't success, you can change the identifier and retry:
$this->ion_auth_model->identity_column = "email";
No modifications in model or library or custom querys neccesary
without having to edit ion_auth_model, you can do something like this:
considering you already have this config:
$config['identity'] = 'username';
and you have this on your controller:
// log the user in
public function login()
{
...
if ($this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember))
{
//if the login is successful
you can let it to check and then if it's not successful, set the email as identity column and check for it:
// log the user in
public function login()
{
...
// check for username
$login = $this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember);
if(! $login) { // username is not successful
$this->ion_auth_model->identity_column = 'email';
// check for email
$login = $this->ion_auth->login($this->input->post('identity'), $this->input->post('password'), $remember);
}
if( $login ) {
// successful
} else {
// both failed
}
the advantage of this: more compatibility with any new update to ionAuth since you didn't change the core files. the downside of this is that's it's have to double query the database.
Auth controller code modified from: ionAuth Auth Controller Example
Discussions on ionAuth Repo:
Issue 510: Switching between username/email as identity
Issue 792: Login with Username or Email
Pull Request 746: Add option for alternate identity column
I recently forked Ion Auth and made the necessary enhancements so that this could be chosen in the configuration. The fork is located here:
https://github.com/zepernick/CodeIgniter-Ion-Auth
I offered up a pull request to get this included in the Ion Auth code base, but it has not been accepted at this time. There was some debate going on about whether it made the code to complex. Please drop them a note and let them know you would like this functionality if it is useful to you.
https://github.com/benedmunds/CodeIgniter-Ion-Auth/pull/746
use 'email' in 'identity' ion_auth config then add this code after $query in ion_auth_model line 866
if($query->num_rows() == 0){
$query = $this->db->select($this->identity_column . ', username, email, id, password, active, last_login')
->where('username', $this->db->escape_str($identity))
->limit(1)
->get($this->tables['users']);
}
I think the easier way would be checking if the $identity var is an email. If it's not an email, then you set the column to 'username'.
Something like this:
$check_column = valid_email($identity) ? $this->identity_column : 'username';
$query = $this->db->select('username, email, id, password, active, last_login')
->where($check_column, $this->db->escape_str($identity))
->limit(1)
->get($this->tables['users']);
In this case, you'll need the email_helper loaded.
Works for me.
Put this on your Controller
if ($this->form_validation->run() !== FALSE) {
$remember = (bool) $this->input->post('remember');
$this->ion_auth_model->identity_column = 'username/email';
if ($this->ion_auth->login($this->input->post('username'), $this->input->post('password'), $remember))
{
$this->session->set_flashdata('message', $this->ion_auth->messages());
}
redirect('auth/login');
}
Edit ion_auth_model.php. find the function login() and the update the
code using the code below.
public function login($identity, $password, $remember=FALSE)
{
$this->trigger_events('pre_login');
if (empty($identity) || empty($password))
{
$this->set_error('login_unsuccessful');
return FALSE;
}
$this->trigger_events('extra_where');
//just add this (starting this line)
if ($this->identity_column == "username/email")
{
$fieldname = explode('/', $this->identity_column);
$query = $this->db->select($fieldname[0] . ', username, email, id, password, active, last_login')
->where($fieldname[0], $identity)
->limit(1)
->get($this->tables['users']);
$this->identity_column = $fieldname[0];
if ($query->num_rows() === 0) {
$query = $this->db->select($fieldname[1] . ', username, email, id, password, active, last_login')
->where($fieldname[1], $identity)
->limit(1)
->get($this->tables['users']);
$this->identity_column = $fieldname[1];
}
}
else
{
$query = $this->db->select($this->identity_column . ', username, email, id, password, active, last_login')
->where($this->identity_column, $identity)
->limit(1)
->get($this->tables['users']);
}
//up to this line
if($this->is_time_locked_out($identity))
{
//Hash something anyway, just to take up time
$this->hash_password($password);
$this->trigger_events('post_login_unsuccessful');
$this->set_error('login_timeout');
return FALSE;
}
if ($query->num_rows() === 1)
{
$user = $query->row();
$password = $this->hash_password_db($user->id, $password);
if ($password === TRUE)
{
if ($user->active == 0)
{
$this->trigger_events('post_login_unsuccessful');
$this->set_error('login_unsuccessful_not_active');
return FALSE;
}
$this->set_session($user);
$this->update_last_login($user->id);
$this->clear_login_attempts($identity);
if ($remember && $this->config->item('remember_users', 'ion_auth'))
{
$this->remember_user($user->id);
}
$this->trigger_events(array('post_login', 'post_login_successful'));
$this->set_message('login_successful');
return TRUE;
}
}
//Hash something anyway, just to take up time
$this->hash_password($password);
$this->increase_login_attempts($identity);
$this->trigger_events('post_login_unsuccessful');
$this->set_error('login_unsuccessful');
return FALSE;
}
You can do this without modifying the core code. Just change the identity column on the fly if a valid email is present. NOTE: ion_auth_model not ion_auth.
public function check_login()
{
if (!$this->input->is_ajax_request()) {
exit('No direct script access allowed');
}
$this->form_validation->set_rules('username', str_replace(':', '', $this->lang->line('login_identity_label')), 'required');
$this->form_validation->set_rules('password', str_replace(':', '', $this->lang->line('login_password_label')), 'required');
if ($this->form_validation->run() == false) {
$this->form_validation->json_errors();
}
$identity = $this->input->post('username');
if ($this->form_validation->valid_email($identity)) {
$this->ion_auth_model->identity_column = 'email';
} else {
$this->ion_auth_model->identity_column = 'username';
}
if ($this->ion_auth->login($identity, $this->input->post('password'), false)) {
encode_response('success');
} else {
encode_response('error', $this->ion_auth->errors());
}
}

Categories