Controller code
How to check email already exist in multiple table in codeigniter
function rolekey_exists($key) {
$this->Register_model->mail_exists($key);
}
Model code
Below shown in the model code i joined two table how to check email already exist before inserting in two different table
function mail_exists($key)
{
$this->db->select('*');
$this->db->from('supplier_registration');
$this->db->join('customer_registration', 'supplier_registration.email = customer_registration.email');
$this->db->where('supplier_registration.email',$key);
$query=$this->db->get();
if ($query->num_rows() > 0){
return true;
}
else {
return false;
}
}
You can use OR condition to check email in multiple tables.
$this->db->select(*);
$this->db->->from('supplier_registration, customer_registration');
$this->db->where('supplier_registration.email',$key);
$this->db->or_where('customer_registration.email',$key);
Hope this will help you.
Change your TRUE and FALSE as well check in controller
In Model
function mail_exists($key)
{
$this->db->select('*');
$this->db->from('supplier_registration');
$this->db->join('customer_registration', 'supplier_registration.email = customer_registration.email');
$this->db->where('supplier_registration.email',$key);
$query = $this->db->get();
if ($query->num_rows() > 0)
{
# email exist
return false;
}
else {
# new/fresh email
return true;
}
}
In Controller
function rolekey_exists($key) {
$result = $this->Register_model->mail_exists($key);
if ($result == TRUE) {
echo "Email Exists";
} else {
echo "New Email";
}
}
Related
It's been few days that I have been trying to learn Codeigniter and while making small applications I came to this point where I have to update DB.
I have inserted data using validations but when it comes to updating, it looks like it is always "FALSE" as those records are already in DB that I am editing. Result, it doesn't take it.
Seeking some help here to overcome this problem.
Validation (Controller):
$this->form_validation->set_rules('v_member_email', 'Email Address', 'trim|required|valid_email|callback_check_if_email_exists');
public function check_if_email_exists($requested_email) {
$email_available = $this->update_model->check_if_email_exists($requested_email);
if ($email_available) {
return TRUE;
} else {
return FALSE;
}}
It always returns "Validation Error" as this email is already in use.
Model:
function check_if_email_exists($email) {
$this->db->where('v_member_email', $email);
$result = $this->db->get('vbc_registered_members');
if ($result->num_rows() > 0){
return FALSE; //Email Taken
} else {
return TRUE; // Available
}}
Yes, because, email is already present.
All you have to do is, pass the is to callback while updating like this,
callback_check_if_email_exists['.$id.']
Id is the database id.
In controller
public function check_if_email_exists($requested_email, $id) {
$email_available = $this->update_model->check_if_email_exists($requested_email, $id);
if ($email_available) {
return TRUE;
} else {
return FALSE;
}
}
In model
if ($id) {
$this->db->where('id !=', $id);
}
$this->db->where('email', $str);
$res = $this->db->get('users');
if ($res->num_rows()) {
return false;
} else {
return true;
}
}
What we are doing here is, if you are passing the id to callback, then
check if the email is present except this id,
If id is not passed, check only for email without considering the id
in your controller you return true if the email exists. and false if not, but in your model you return false if exists and true if not.
$this->form_validation->set_rules('v_member_email', 'Email Address', 'trim|required|valid_email|callback_check_if_email_exists');
public function check_if_email_exists($requested_email) {
$email_available = $this->update_model->check_if_email_exists($requested_email);
// here you check if the return from the model is true or false if true the email exists otherwise the email not exists
if ($email_available) {
return TRUE; // here true mean the email is exists and not Available
} else {
return FALSE; // here it mean the email not exists and Available
}}
and that's the problem you should return true in your model if the email exists to make it work.
function check_if_email_exists($email) {
$this->db->where('v_member_email', $email);
$result = $this->db->get('vbc_registered_members');
if ($result->num_rows() > 0){
return true; // here true mean the email is exists and not Available
} else {
return false; // here it mean the email not exists and Available
}
}
I am new to php framework i have created a simple form and want to inserts its value in database but failed to do so don't know where i am wrong!!!
Every time i am getting MySQL returned an empty result set (i.e. zero rows).
i am using CodeIgniter 3 and mysqli drivers this is my Controller
<?php
//display_errors(on);
error_reporting(E_ALL);
class Register extends CI_Controller {
public function index () {
//Validations
$rules=array (
"username"=> array(
"field"=>"username",
"label"=>"Username",
"rules"=>"required|max_length[20]|min_length[5]|callback_username_is_taken"
),
"password"=> array(
"field"=>"password",
"label"=>"Password",
"rules"=>"required|max_length[20]|min_length[6]"
),
"pass_conf"=> array(
"field"=>"pass_conf",
"label"=>"Password",
"rules"=>"required|matches[password]"
),
"email"=> array(
"field"=>"email",
"label"=>"Email",
"rules"=>"required|valid_email|callback_is_taken"
)
);
//set the rules
$this->form_validation->set_rules($rules);
//Override the message
$this->form_validation->set_message('required','The %s field is empty');
// check to see if form has been submitted
if ($this->form_validation->run()!=true) {
$this->load->helper('url');
$this->load->view('register'); //Display page
$this->load->view('footer');
}else {
echo "Donkey Butt";
$form=array();
$form['username']=$this->input->post("username");
$form['password']=md5($this->input->post("password"));
$form['email']=$this->input->post("email");
if(self::createUser($form['username'],$form['password'],$form['email'])==true) {
//Created User Successfully
echo "Success";
//$this->load->view("success",$data);
}else{
echo "problem in subbmitting the form";
}
}
}
public function username_is_taken($input) {
$query="SELECT * FROM `tbl_usrs` WHERE `username`=? ";
$arg=array ($input);
$exec=$this->db->query($query,$arg) or die(mysqli_error());
echo $query;
if($exec->num_rows() >0)
{
$this->form_validation->set_message('username_is_taken','Sorry the UserName <b> $input </b> is already taken');
return false;
}else {
return true;
}
}
public function email_is_taken($input) {
$query="SELECT * FROM `tbl_usrs` WHERE `email`=? ";
$arg=array ($input);
$exec=$this->db->query($query,$arg) or die(mysqli_error());
echo $query;
if($exec->num_rows() >0)
{
$this->form_validation->set_message('email_is_taken','Sorry the email <b> $input </b> is already taken');
return false;
}else {
return true;
}
}
public function createUser($user,$pass,$email)
{
$query="
INSERT INTO `tbl_usrs` (`username`,`password`,`email`,`ip`)
VALUES (?,?,?,?)
";
$arg=array (self::protect($user),self::protect($password),$email,$_SERVER['REMOTE_ADDR']);
if($this->db->query($query,$arg)==true)
{
echo $query;
return true; // if added to database
}else {
return false;
}
}
public function protect($str) {
return mysqli_real_escape_string($str);
}
}
?>
fixing mysqli_real_escape_string($str); //excepts two parameters only one given
fixing is this make your code work
So here's what I want to do. I want to check if the userid in segment(3) exist or else it will redirect somewhere instead of still loading the view with an error.
Here's the example url
http://localhost/ems/edit_user/edit_user_main/1001
Now if I try to edit the userid in segment(3) and intentionally put an invalid userid, it still loads the view and i don't know why
Here's my function
public function edit_user_main(){
$id = $this->uri->segment(3);
$check = $this->get_data->check_if_exist($id);
if($check) {
$data['title'] = 'Edit User';
$data['id'] = $this->session->userdata('usertoedit');
$this->load->model('accounts/get_data');
$item = $this->get_data->get_user($id);
$data['user'] = $item[0];
$data['main_content'] = 'edit_user/edit_user_main';
$this->load->view('includes/template', $data);
} else {
redirect('admin/adminuser');
}
}
Here's the model
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query) {
return TRUE;
} else {
return FALSE;
}
}
There is no problem with the fetching of data.
The problem is even if the userid doesn't exist, the view is still loading but with an error coz there's no data for that userID. It's not redirecting,
I tried using print_r and it working fine, the value of the $check is 1 when there's a valid userID.
Hope someone can help me with this. Thank you
With your function it will always return true because the statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always execute,So you need to check query is returning any result row or not with the statement
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
Try this..
With the function it will always return true because the following statement
$this->db->get_where('accounts',array('user_id'=>$id));
will always be execute, So need to check query is returning any result row or not
$query->num_rows().
public function check_if_exist($id){
$query = $this->db->get_where('accounts',array('user_id'=>$id));
if($query->num_rows() > 0){ //change made here
return TRUE;
}
else{
return FALSE;
}
}
And load heper as:-
$this->load->helper('url');
before the redirection
I don't know why this don't work at all. I maybe wrong with my understanding that is why.
here is the situation.
MVC pattern
form validation stuffs
Here are the codes
public function userExist($data)
{
$string = "SELECT student_number FROM users WHERE student_number = :user";
$sth = $this->db->prepare($string);
$sth->execute(array(
':user' => $data['user']
));
return $sth->rowCount() == 0 ? true : false;
}
public function validate($data) {
$this->userExist($data);
}
What i want is to return a string, that says "user exists", if the userExist method is false ... But this code doesn't work:
if($sth->rowCount() == 0) {
return true;
} else {
return "User Already Exists";
}
This is, how i call them in the controller:
if ($this->model->validate($data) == true) {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
echo $this->model->validate($data);
die();
}
What do you think is the best solution?
First of all, you need to return the value of validate:
public function validate($data) {
$this->userExist($data);
}
But there are some other problems here. You don't need to call $this->model->validate($data) twice in your controller. You could do something like:
$result = false;
$result = $this->model->validate($data);
if ( true === $result {
$this->model->create($data);
header('Location: '.URL.'users');
} else {
die($result);
}
I created a helper for returning a user's username if the user's unique id is known.
if ( ! function_exists('get_username'))
{
function get_username($user_id)
{
$ci=& get_instance();
$ci->load->database();
if (empty($user_id))
{
return FALSE;
}
$ci->db->select('username');
$ci->db->where('id', $user_id);
$ci->db->where('activated', 1);
$ci->db->where('banned', 0);
$ci->db->limit(1);
$query = $ci->db->get('users');
if ($query->num_rows() > 0) //if user exists
{
$row = $query->row();
return $row->username;
}
else
{
return FALSE;
}
}
}
This works in my view if for instance I try:
echo get_username($this->uri->segment(3)); //uri segment 3 is a user id.
However want to send the username to my view via controller. I tried the following in my controller:
function write_message($user_id = '') //function parameter is 3rd uri segment
{
$data['username'] = get_username($user_id);
$this->load->view('my_view', $data);
}
Then in my view I have
echo $username which echoes array instead of the username. What am I doing wrong here?
Your criteria should be clear, and the usrname should be unique i think, so...
if ($query->num_rows() == 1) //if user exists, and unique
{
$res = $query->result_array();
return $res[0]['username'];
}
else
{
return FALSE;
}
Upon using <pre>print_r($username)</pre> in my view (as suggested by Alfonso) it was easy to spot the issue, being an identical variable name in my view which was another array. Correct answer goes to anyone that gives a good suggestion/input for my helper or Alfonso if he submits his post as answer.