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
}
}
Related
I am developing a Register/Login system with validation. Registering system is working well. For example, when I register the same email twice, the following message appears:
Email already registered!
However, when I log-in with the same e-mail and password, an error occurs. The following message appears as a validation error:
Email not registered!
Even if the email is registered in DB.
Code for e-mail validation:
<?php
public function validateEmail($par)
{
if (filter_var($par, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
$this->setErro("Invalid Email!");
return false;
}
}
public function validateIssetEmail($email, $action = null)
{
$b = $this->cadastro->getIssetEmail($email);
if ($action == null) {
if ($b > 0) {
$this->setErro("Email already registered!");
return false;
} else {
return true;
}
} else {
if ($b > 0) {
return true;
} else {
$this->setErro("Email not registered!");
return false;
}
}
}
Code for login controller:
<?php
$validate = new Classes\ClassValidate();
$validate->validateFields($_POST);
$validate->validateEmail($email);
$validate->validateIssetEmail($email,"login");
$validate->validateStrongSenha($senha);
$validate->validateSenha($email,$senha);
var_dump($validate->getErro());
Code for class login:
<?php
namespace Models;
class ClassLogin extends ClassCrud
{
# Returns user data
public function getDataUser($email)
{
$b = $this->selectDB(
"*",
"users",
"where email=?",
array(
$email
)
);
$f = $b->fetch(\PDO::FETCH_ASSOC);
$r = $b->rowCount();
return $arrData = [
"data" => $f,
"rows" => $r
];
}
}
My getIssetEmail method exists on Register code only.
# Check directly at the bank if the email is registered
public function getIssetEmail($email)
{
$b = $this->selectDB(
"*",
"users",
"where email=?",
[
$email
]
);
return $r = $b->rowCount(); // returns the amount of rows in the search
}
And ClassPassword
<?php
namespace Classes;
use Models\ClassLogin;
class ClassPassword
{
private $db;
public function __construct()
{
$this->db = new ClassLogin();
}
# Create password's hash to save in DB
public function passwordHash($senha)
{
return password_hash($senha, PASSWORD_DEFAULT);
}
# Verify if password's hash is correct
public function verifyHash($email, $senha)
{
$hashDb = $this->db->getDataUser($email);
return password_verify($senha, $hashDb["data"]["senha"]);
}
}
This is not an answer but hopefully it will help in debugging.
First, I'm going to change your code. This is 100% a style choice but I personally think it is easier to follow. If you have an if statement that always returns, you don't technically need an else. Once again, this is a style choice and you don't have to follow it.
Second, if you can, try adding logging into your workflow, it will save you so much time debugging. It isn't always an option, especially for legacy code bases, but it is awesome when you can inspect complex code. In this example, I"m just making a couple of helper methods that dump stuff but normally I'd use something like Monolog to write to a stream that I can tail, and I can easily turn it off in production. When logging, sometimes it helps to avoid identical messages so that you can easily find the exact line number you are on, too.
So with those changes, try running this code inside of your class:
private function logMessage($message)
{
echo $message . PHP_EOL;
}
private function logVariable($variable)
{
var_dump($variable);
}
public function validateIssetEmail($email, $action = null)
{
$this->logVariable($email);
$this->logVariable($action);
$b = $this->cadastro->getIssetEmail($email);
$this->logVariable($b);
if ($action === null) {
$this->logMessage('Action was null');
if ($b > 0) {
$this->logMessage('B is greater than zero');
$this->setErro("Email already registered!");
return false;
}
$this->logMessage('B was not greater than zero');
return true;
}
$this->logMessage('Action was not null');
if ($b > 0) {
$this->logMessage('B is greater than zero');
return true;
}
$this->logMessage('B was not greater than zero');
$this->setErro("Email not registered!");
return false;
}
This should log in human-readable form every step. You should be able to walk through this and identify where your bug is. For instance, in the comments above you said that a variable was 0 in a block that was guarded by a check that guarantees that that shouldn't happen.
This is the wrong part i guess you assigned login as action so you can call cadastro class inside of the function
$cadastro = new Cadastro();
$b = $cadastro->getIssetEmail($email);
if ($action == null) {
if ($b > 0) {
$this->setErro("Email already registered!");
return false;
} else {
return true;
}
} else {
if ($b > 0) {
return true;
} else {
$this->setErro("Email not registered!");
return false;
}
}
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";
}
}
I am writing a method that uses POST variables posted by AJAX to add a user to a certain course in the database, but I can't get the callback to work correctly:
public function enroll()
{
$package = array();
$this->load->library('form_validation');
$this->form_validation->set_rules('course', 'Vak', 'required|callback_not_enrolled');
$fields = array("course");
if ($this->form_validation->run($this) === FALSE) {
$errors = array();
$success = array();
foreach ($fields as $field) {
$error = form_error($field);
if ($error !== "") {
$errors[$field] = $error;
} else {
$success[$field] = True;
}
}
$package["field_errors"] = $errors;
$package["field_success"] = $success;
$package["success"] = False;
} else {
$package["database"] = $this->course_model->enroll_user($this->data["user"], $this->input->post("course"));
$package["success"] = True;
}
echo json_encode($package);
}
I wrote the callback not_enrolled to check if the user is not already enrolled to the database. Note that I can't use is_unique because I have to test the combined uniqueness of two fields (so just one or two separate ones don't do the trick) and the id of the user is not included in the form (because it's part of the Code Igniter session).
The callback function:
public function _not_enrolled($course)
{
$exists = ($this->user->is_enrolled($course, $this->data["user_id"]) != False);
if ($exists != False) {
$this->form_validation->set_message("not_enrolled", "Already enrolled");
return False;
} else {
return True;
}
}
And finally the method is_enrolled from the model:
public function is_enrolled($course, $user=False) {
if($user==False){
$user = $this->data["user_id"];
}
$this->db->select()->from("course_participant")->where("user_id", $user)->where("course_id", $course);
$query = $this->db->get();
return($query->num_rows()>0);
}
Through a call to var_dump($this->_not_enrolled($existing_course_id)); I know that both the callback function and the method from the model work, as it correctly returned true.
When I var_dump the $package array or validation_errors() I don't get any validation errors except that it says Unable to access an error message corresponding to your field name Vak(not_enrolled).
I tried removing the initial _ from the function name but that gives me a Server Status 500 error.
I have another setup exactly like this, albeit other database calls, with a callback using the same syntax. This method works perfectly.
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);
}