how to check if username already exists in codeigniter - php

I am working on a site in codeigniter.I am not so expert using framework.Here I have to check if email already exists in database.I have coded the required functionality but I am getting an error when submit the form.
In controller i have made the following rule.
My code is:
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique|callback_isEmailExist'
);
public function isEmailExist($email) {
$this->load->library('form_validation');
$this->load->model('user');
$is_exist = $this->user->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message(
'isEmailExist', 'Email address is already exist.'
);
return false;
} else {
return true;
}
}
in model user the function is :
function isEmailExist($email) {
$this->db->select('id');
$this->db->where('email', $email);
$query = $this->db->get('users');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
When I submit the form, I am getting the following errors.
A PHP Error was encountered
Severity: Notice
Message: Undefined offset: 1
Filename: libraries/Form_validation.php
Line Number: 953
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE ` = 'muraddnw#gmail.com' LIMIT 1' at line 2
SELECT * WHERE ` = 'muraddnw#gmail.com' LIMIT 1
Filename: C:\xampp\htdocs\aunction\system\database\DB_driver.php
Line Number: 330
Anyone help me please.
Thanks in advance.

Your problem is in the set_rules line. Here you use both is_unique and a callback function. You have to use anyone of that. If you use a call_back function to check duplicate data; doesn't need to use is_unique. For this wrong you get that error Just remove the is_unique from there.
$this->form_validation->set_rules('email','Email','trim|required|valid_email|callback_isEmailExist'); // removed is_unique
Try this out and let me know.

$this->form_validation->set_rules('username', 'userName', 'required|callback_exists_username');
#uniqueness of username
function exists_username($str)
{
$record_id = $this->input->post('record_id');
$condition = array('user_id !='=>$record_id,'username'=>$str);
$value =GetAllRecord('user_master',$condition,$is_single=true);
if (count($value) == 0)
{
return TRUE;
}
else
{
$this->form_validation->set_message('exists_username', 'username already exists!');
return FALSE;
}
}

Just add is_unique[tablename.fieldname] rules to the form validation. for Example:
array('field' => 'email', 'label' => 'Email', 'rules' => 'trim|required|valid_email|is_unique[users.email]'));

Your Model is like
$this->db->select('id');
$this->db->where('email', $email);
please tell the mysql from which table you want to get the record.
$this->db->from('tablename');
it would be like
$this->db->select('id');
$this->db->from('tablename');
$this->db->where('email', $email);

You have an error in the mysql query:-
SELECT * WHERE ` = 'muraddnw#gmail.com' LIMIT 1
Your code has not specified which table to query from. So use following:-
$this->db->select('id');
$this->db->from('tablename');
$this->db->where('email', $email);
Hope this helps.

no need to a make a special function, this is enough
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique'
);

Use is_unique[table.field] add table name and field.
$this->form_validation->set_rules(
'email', 'Email', 'trim|required|valid_email|is_unique[table.field]|callback_isEmailExist'
);

you can check if a field is unique or not by using form_validator function is_unique[table_name.field_name]

Related

Message: Undefined variable: email under Controllers

I am getting Undefined Variable email under Controllers.
Controller : login.php
public function index() {
$this->load->view('bootstrap/header');
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->load->model('Login_db');
$is_exist = $this->Login_db->isEmailExist($email);
if ($is_exist) {
$this->form_validation->set_message('isEmailExist', 'Email Address Already Exists!');
return FALSE;
} else {
return TRUE;
}
$this->load->view('bootstrap/footer');
}
Model : login_db.php
public function isEmailExist($email) {
$this->db->select('user_id');
$this->db->where('email', $email);
$query = $this->db->get('login');
if ($query->num_rows() > 0) {
return TRUE;
} else {
return FALSE;
}
}
I have to check whether email exists are not.
before
$is_exist = $this->Login_db->isEmailExist($email);
add this (in case of a POST request)
$email = $this->input->post('email');
or this ((in case of a GET request)
$email = $this->input->get('email');
by checking your code i came to assume that you want to allow only the emails which is already not in table ? why have not you validated with is_unique like
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[login.email]');
or you can change the line as
$this->Login_db->isEmailExist($this->input->post('email'));
or you should define $email before passing it / calling the function
$email=$this->input->post('email');
for custom massaging :
$this->form_validation->set_rules( 'email', 'Email', 'required|valid_email|is_unique[login.email]', array( 'is_unique' => 'Email already exists' ) );
better you go through the manual
https://www.codeigniter.com/user_guide/libraries/form_validation.html
the var $email used here
$is_exist = $this->Login_db->isEmailExist($email); line 5 of index
is never isntanciate. You should instantiate it to avoir error.

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();

getting the query from database - Codeigniter

I wanted to check whether the username exists in the database,
but Codeigniter is throwing an
Error: Can't use method return value in write context.
The code is as follows:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if(empty($query->row_array())){
return true;
}else{
return false;
}
}
$result = $query->row_array();
if(empty($result)){
return true;
}else{
return false;
}
try using below code
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if($query->num_rows() > 0){
return true;
}else{
return false;
}
}
It looks like you are trying to validate a form for user registration. If this is the case, then you would be far better off using the built-in form_validation library (https://codeigniter.com/user_guide/libraries/form_validation.html). There is already a built in method that would help you make sure you have unique records (such as the username). So basically, once the form_validation library is loaded, you would need to set the rules for validation. Once rules are set, you can call the run() method, which will produce a bool true/false whether it passes validation or not.
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', "trim|required|is_unique[users.username]");
if($this->form_validation->run() === true) {
//Do something when posted form is validated
} else {
// There were errors or this is the first time
if(validation_errors())
$data['error_message'] = validation_errors();
}
You should use the form validation library to validate any (and usually all) of your forms throughout your application
Hope that helps
First Understand the Error: Can't use method return value in write context.
empty() needs to access the value by reference (in order to check whether that reference points to something that exists).
However, the real problem you have is that you use empty() at all, mistakenly believing that "empty" value is any different from "false".
Empty is just an alias for !isset($thing) || !$thing. When the thing you're checking always exists (in PHP results of function calls always exist), the empty() function is nothing but a negation operator.
Not Coming to your problem, As Scott Miller suggest you can use CodeIgniter validation. And if you want a little advance solution then you can put your validation in the config folder with creating form_validation.php for more detail visit CodeIgniter documentation for validation.
$config = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required|is_unique[users.username]'
)
);
And If you want to do it with the query then here is the query:
public function check_username_exists($username){
$query = $this->db->get_where('users', array('username' => $username));
if ($query->num_rows() > 0){
return true;
}
else{
return false;
}
}
You can use num_rows to get the username exist or not.

Codeigniter Form Validation Callback Function

I'm trying to create a form validation callback function but I'm having a little trouble getting my head around it.
What I am trying to do is create a contact form where with a join the mailing list option. If the option to join the mailing list is checked I want the name and email of the person to be added to the mailing list database. This part works perfectly however I also want the function to check the database to ensure that the email address being added is unique and this is the bit that I just can't get my head around.
Controller:
public function contact()
{
$this->load->helper('form');
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'your name', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
$this->form_validation->set_rules('email', 'your email address', 'required', array('required'=>"<p class='required'>Please provide %s</p><br>"));
if($this->form_validation->run() == FALSE)
{
$this->load->view('templates/headder');
$this->load->view('contact');
$this->load->view('templates/footer');
}
else
{
$this->load->library('email');
$name = $this->input->post('name');
$email = $this->input->post('email');
$phone = $this->input->post('phone');
$message = $this->input->post('message');
$list = $this->input->post('mailing_list');
$email_message = "Name: $name<br>Email: $email<br>Phone: $phone<br>Message:<br>$message";
$this->email->initialize();
$this->email->from($email, $name);
$this->email->to('myaddress#mydomain.co.uk');
$this->email->subject('New Query');
$this->email->message($email_message);
$this->email->send();
if($this->email->send()){
$this->load->view('send_error');
}
else
{
if($list == 'no')
{
$this->load->view('sent');
}
else
{
$this->form_validation->set_rules('email', 'Email', 'is_unique[mail_list, email]');
if($this->form_validation->run() == FALSE)
{
$this->load->model('mailing_listm');
$this->mailing_listm->add_name();
$this->load->view('sent');
}
else
{
$this->load->view('contact');
}
}
}
}
}
Error Message:
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' email 'myaddress#mydomain.co.uk' LIMIT 1' at line 3
SELECT * FROM `mail_list`, `email` WHERE mail_list, email 'myaddress#mydomain.co.uk' LIMIT 1
Filename: libraries/Form_validation.php
Line Number: 1134
Hopefully someone will be able to let me know what daft thing I've done this time.
Also, This function is turning into a bit of a monster, it's the most complicated thing I've every tried to write. Is there any way that I can split it out so that it is made up of several smaller functions instead of one gargantuan one?
Thanks,
EDIT
I have updated my code in line with the comment below about using is_unique however now I am receiving an error message.
EDIT
Model:
Public function add_name()
{
$this->name = $this->input->post('name');
$this->email = $this->input->post('email');
$this->db->insert('mail_list', $this);
}
for checking unique field there is a validation rule in codeigniter.
is_unique[table.field]

Codeigniter form validation error message

I have a form on my website header where i allow the user to log in with his username/password... then i POST to /signin page and check if the username exists to allow the user to log in.. if there is a problem upon login i output these errors...
i tried using the following code to show a custom error but with no luck
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$this->form_validation->set_message('new_error', 'error goes here');
//error
}
$this->load->view("login/index", $data);
}
how does set_message work and if this is the wrong method, which one allow me to show a custom error in this case?
EDIT :
validation rules:
private $validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'trim|required|callback__check_valid_username|min_length[6]|max_length[20]|xss_clean'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'trim|required|min_length[6]|max_length[32]'
),
);
The set_message method allows you to set your own error messages on the fly. But one thing you should notice is that the key name has to match the function name that it corresponds to.
If you need to modify your custom rule, which is _check_valid_username, you can do so by perform set_message within this function:
function _check_valid_username($str)
{
// Your validation code
// ...
// Put this in condition where you want to return FALSE
$this->form_validation->set_message('_check_valid_username', 'Error Message');
//
}
If you want to change the default error message for a specific rule, you can do so by invoking set_message with the first parameter as the rule name and the second parameter as your custom error. E.g., if you want to change the required error :
$this->form_validation->set_message('required', 'Oops this %s is required');
If by any chance you need to change the language instead of the error statement itself, create your own form_validation_lang.php and put it into the proper language folder inside your system language directory.
As you can see here, you can display the custom error in your view in the following way:
<?php echo form_error('new_error'); ?>
PS: If this isn't your problem, post your corresponding view code and any other error message that you're getting.
The problem is that your form is already validated in your IF part! You can fix the problem by this way:
if ($this->form_validation->run() == false){
$this->load->view("login/index", $data);
}else{
$return = $this->_submitLogin();
if ($return == true){
//success
}else{
$data['error'] = 'Your error message here';
//error
}
$this->load->view("login/index", $data);
}
In the view:
echo $error;
The CI way to check user credentials is to use callbacks:
$this->form_validation->set_rules('username', 'Username', 'callback_username_check');
...
public function username_check($str) {
// your code here
}
I recommend you to read CI documentation: http://codeigniter.com/user_guide/libraries/form_validation.html
The way I did this was to add another validation rule and run the validation again. That way, I could keep the validation error display in the view consistent.
The following code is an edited excerpt from my working code.
public function login() {
$this->form_validation->set_rules('email', 'Email', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
$data['content'] = 'login';
if($this->form_validation->run()) {
$sql = "select * from users where email = ? and password = ?";
$query = $this->db->query($sql, array($this->input->post('email'), $this->input->post('password')));
if($query->num_rows()==0) {
// user not found
$this->form_validation->set_rules('account', 'Account', 'callback__noaccount');
$this->form_validation->run();
$this->load->view('template', $data);
} else {
$this->session->set_userdata('userid', $query->id);
redirect('/home');
}
} else {
$this->load->view('template', $data);
}
}
public function _noaccount() {
$this->form_validation->set_message('_noaccount', 'Account must exist');
return FALSE;
}
Require Codeigniter 3.0
Using callback_ method;
class My_controller extends CI_Controller {
function __construct() {
parent::__construct();
$this->form_validation->set_message('date_control', '%s Date Special Error');
}
public function date_control($val, $field) { // for special validate
if (preg_match("/^[0-9]{2}.[0-9]{2}.[0-9]{4}$/", $val)) {
return true;
} else {
return false;
}
}
public function my_controller_test() {
if ($this->input->post()) {
$this->form_validation->set_rules('date_field', 'Date Field', 'trim|callback_date_control[date_field]|xss_clean');
if ($this->form_validation->run() == FALSE) {
$data['errors']=validation_errors();
$this->load->view('my_view',$data);
}
}
}
}
Result:
if date = '14.07.2017' no error
if date = '14-7-2017' Date Field Date Special Error

Categories