Codeigniter Form Validation Callback Function - php

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]

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

how i should update the email?

This is my validation for updating the email..
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|callback__unique_email[email]');
The call back function is
public function _unique_email($email) {
if ($this->crud_model->fetch_user_by_email_user_id($email,$this->session->userdata('user_id'))) {
return true;
} else {
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|is_unique[users.email]');
return true;
return false;
}
}
the email should be updated if the user changes the email in profile settings but if the user not makes any changes the email should be the old one and if he changes the email then it should be update by checking weather the email is unique in the database or not??
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|callback_email_check');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('form');
}
else
{
if($this->update($email)){
$this->load->view('formsuccess');
}
}
}
I haven't used codeIgniter for years, So I don't exactly know how things are there. But I'll try to answer your question on a general context and try to express that using the same code in your question with minor changes.
When You want to check if the user changed his email or not you need to have his old email from database first or in a hidden field of the form, then compare the email field value with the old one will make you know if he changed it.
Second you need to check if the email have duplicates on the database, remember you need to do this only if the user changed his email address, so just run a query with the database. if there are no existing email update the user email in database else display an error and quit.
public function is_unique_email($email) {
$old_email = $this->crud_model->fetch_user_email($this->session->userdata('user_id'));
if ($old_email == $email) {
return true;
} else {
$duplicates = $this->crud_model->fetch_user_by_email($email);
if(count($duplicates) > 0)
{
return false;
}
else
{
return true;
}
}
}
The end code should something similar to this, I'm sorry I can't give you the exact code, But I think you can run with this approach.
I suggest you to move to some good frameworks like symfony, laravel or
zend. Codeigniter is not improved much from those early days where PHP
did a lot.

how to check if username already exists in codeigniter

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]

CodeIgniter form validation valid_email not working

I am trying to use CodeIgniter's form validation class. I've used the "valid_email" parameter, as can be seen from the code below, but even when an invalid email address is entered it still passes the validation check. I tested with the string: testing123
public function login()
{
$this->form_validation->set_rules('authEmail', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'trim|required');
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
if($this->form_validation->run() === FALSE) {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
} else {
// Begin authentication
}
}
Anyone have any idea what I'm doing wrong or if this is a CodeIgniter issue?
To note, I am setting a flashdata session as opposed to using:
<?php echo validation_errors(); ?>
... this is because I am doing a redirect back to the homepage (which is the login page as it's a private site).
Try this:
public function login()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('authEmail', 'Email', 'trim|required|valid_email|xss_clean');
$this->form_validation->set_rules('authPassword', 'Password', 'trim|required');
if($this->form_validation->run() !== false){
//validation passed
$email = $this->input->post('authEmail');
$password = $this->input->post('authPassword');
// Begin authentication
}
else {
$this->session->set_flashdata('formValidationError', validation_errors('<p class="error">', '</p>'));
redirect('/');
}
}
I'm just learning to use it as well, but don't you need three parameters? This is from their form validation page:
$this->form_validation->set_rules('email', 'Email', 'required');
From http://codeigniter.com/user_guide/libraries/form_validation.html#validationrules
The field name - the exact name you've given the form field.
A "human" name for this field, which will be inserted into the error message. For example, if your field is named "user" you might give it a human name of "Username". Note: If you would like the field name to be stored in a language file, please see Translating Field Names.
The validation rules for this form field.

Categories