how to check callback validation codeigniter duplicate database entry? - php

This is my callback function, I want to check the database for duplicate value, I have tried a lot, but I can't get validation to work. I'm new to Codeigniter so any help would be appreciated!
public function alias_exist_check()
{
$scol_code = $this->input->post('school_code');
$user_id=$this->input->post('user_id');
$query=$this->db->get_where('user_application',array('school_code'=>$scol_code, 'user_id'=>$user_id));
$row= $query->row_array();
if(!$row['user_id']==$user_id && !$row['school_code']==$scol_code)
{
return TRUE;
} else {
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return FALSE;
}
}
UPDATE1 ::
i tried this but its not working me help me if i wrote any mistakes.
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check', 'trim|xss_clean'); $where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('post'));
if( ! $this->lawschool_model->alias_exist_check($where))
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
}
if ($this->form_validation->run() == FALSE)
{
$data['row']= $this->lawschool_model->Getuser($data1);
$data['row1']= $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
else
{
$insert = $this->db->insert('user_application',$data);
if($insert==TRUE)
{
/*$idNum = $this->input->post('school_code');
$data1 = $this->lawschool_model->upddata_school();*/
$data['row'] = $this->lawschool_model->Getuser($data1);
$data['row1'] = $this->lawschool_model->GetData1();
$this->ag_auth->view('Home',$data);
}
}
UPDATE2::finaly its works fine,here is my working code
$this->form_validation->set_rules('school_code', 'School Name','required','callback_alias_exist_check1', 'trim|xss_clean');
function alias_exist_check1($scol_code,$user_id)
{
$sql = "SELECT * FROM user_application WHERE school_code = ? AND user_id = ?";
$val = $this->db->query($sql,array($scol_code ,$user_id ));
if ($val->num_rows)
{
$this->form_validation->set_message('alias_exist_check', 'Already exists.');
return TRUE;
}
else
{
return FALSE;
}
}

Model
public function alias_exist($where)
{
return $this->db->where($where)->count_all_results('user_application') > 0;
}
Controller
public function alias_exist_check()
{
$where = array(
'school_code' => $this->input->post('school_code'),
'user_id' => $this->input->post('user_id')
);
return ! $this->name_model->alias_exist($where);
}

The first function was not working because you tried to access post data from within the callback itself. This does not appear to work well with callbacks. This is because codeigniter will remove all post data from the request as soon as your run the form validator run method. It repopulates post data only when form processing is complete. Pass any extra parameters you need for you callback functions to work like this
callback_foo[bar]

Related

how to run two statements in one funcation

I'm trying to delete from two tables using one function.
Controller code:
public function userdelete()
{
$u_id = $this->uri->segment(3);
$lr_id = $this->uri->segment(3);
$returndata = $this->user_model->user_delete($u_id, $lr_id);
if($returndata) {
$this->session->set_flashdata('successmessage', 'user deleted successfully..');
redirect('users');
} else {
$this->session->set_flashdata('warningmessage', 'Something went wrong..Try again');
redirect('users');
}
}
Modle code:
public function user_delete($lr_id, $u_id ) {
return $this->db->delete('login_roles',['lr_id'=>$lr_id]);
return $this->db->delete('login',['u_id'=>$u_id]);
}
I'm able to delete only from the first table but not the other one. this is working :
return $this->db->delete('login_roles',['lr_id'=>$lr_id]); but not return $this->db->delete('login',['u_id'=>$u_id]);.
As said in the comment you have to remove the first return.
You should compute the two results :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return ($delete1Response AND $delete2Response);
}
It will returns true only if both are deleted
You even can go further and :
public function user_delete($lr_id, $u_id ) {
$delete1Response = $this->db->delete('login_roles',['lr_id'=>$lr_id]);
$delete2Response = $this->db->delete('login',['u_id'=>$u_id]);
return (object)array('role' => $delete1Response, 'user' => $delete2Response);
}
Then you can access to data like that :
$response = user_delete(...);
if ($response->role AND $response->user) {
// All fine
} else {
// One or both failed.
// Display error or do something
}
It never reaches the second $this->db->delete since its returns after executing the first one. Try:
public function user_delete($lr_id, $u_id ) {
if($this->db->delete('login_roles',['lr_id'=>$lr_id])){
//success, try the next one
return $this->db->delete('login',['u_id'=>$u_id]);
}
//failed
return false;
}

how to pass the data in the post so that we can call the id?

how to pass the data in the post so that we can call the id ?
because we are trying to get the "qtopic_id" of the question but its not working and it keeps on giving me a null value.
I have tried declaring qtopic_id= 19 to see if its saving in the qtopic_id column.
I don't have to put a specific id value to save on the following column so that it wont save on that specific id only but instead it will save on its corresponding qtopic_id.
controller
public function addChoices(){
$this->form_validation->set_rules('ques','Question','required');
$this->form_validation->set_rules('ch_des1','Choices','required');
$this->form_validation->set_rules('ch_des2','Choices','required');
$this->form_validation->set_rules('ch_des3','Choices','required');
$this->form_validation->set_rules('ch_des4','Choices','required');
$this->form_validation->set_rules('ans','Answer','required');
$this->form_validation->set_error_delimiters('<div class="text-danger">','</div>');
if($this->form_validation->run() ){
echo $qtopic_id ;
$data['ques'] = ($this->input->post('ques'));
$data['ch_des1'] = ($this->input->post('ch_des1'));
$data['ch_des2'] = ($this->input->post('ch_des2'));
$data['ch_des3'] = ($this->input->post('ch_des3'));
$data['ch_des4'] = ($this->input->post('ch_des4'));
$data['ans'] = ($this->input->post('ans'));
if($id=$this->queries->registerChoices($data) )
{
$this->session->set_flashdata('message','Test Added Succesfully');
return redirect('admin/testtwo');
}
else {
$this->session->set_flashdata('message','Failed to Add Test');
}
return redirect('admin/testtwo');
}
else {
$this->addQuestion();
}
}
}
model:
----updated---
public function registerChoices($data) {
echo $this->input->post('qtopic_id');
$question_arr = [
'ques' => $data['ques'],
'qtopic_id' => 19
];
$choices_arr = [
'ques' => $data['ques'],
'ch_des1' => $data['ch_des1'],
'ch_des2' => $data['ch_des2'],
'ch_des3' => $data['ch_des3'],
'ch_des4' => $data['ch_des4'],
'ans' => $data['ans']
];
// echo "<pre>";
// var_dump($question_arr);
// var_dump($choices_arr);
// exit;
$this->db->insert('tbl_choices',$choices_arr);
$this->db->insert('tbl_question',$question_arr);
return $this->db->insert_id();
}
error messages that i encountered
Your code for register choices is a bit unclear. insert_id isn't a function that accepts data nor does it do inserting, it simply returns the last inserted id after you perform an insert query. I think what you want is something like:
function registerChoices($data) {
if ($this->db->insert('tablename', $data)) {
return $this->db->insert_id();
}
return false;
}
Usage:
$last_insert_id = $this->somemodel->registerChoices($data);
if ($last_insert_id) {
echo "item with id $last_insert_id was created!";
} else {
show_error('Query failed!');
}

Can't set error message in Code Igniter 3 when using callback function

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.

how to set custom validation message in grocery crud

$crud = new grocery_CRUD();
$crud->set_table('generate_eblskyid');
$crud->set_rules('salt', 'Salt Code','callback_check_salt');
$output = $crud->render();
then in the call back function i did the following
function check_salt($str)
{
$salt = $_POST['salt'];
if($salt > 5)
{
$this->get_form_validation()->set_message('salt',"Salt value must be less then FIVE");
return FALSE;
}
}
When I go to add record if I give a salt value below five the is inserted successfully but when I give a value greater then five it says "An error has occurred in insert" without displaying my custom message.
What I am doing wrong ??
Your check_salt($str) function should be like this
function check_salt($str)
{
if($str > 5)
{
$this->form_validation->set_message('check_salt',"Salt value must be less then FIVE");
return false;
}else{
return true;
}
}
In set_message function, the callback function name 'check_salt' should be given, not the field name 'salt' This should solve your problem.
This was the only way that I found to makes this work using:
CI 3 and Grocery Crud 1.6.1
$crud->set_rules('name', 'Name', array(
'required',
array(
'company_check',
function ($str) {
$company = $this->Company_model->searchCompanyByName($str);
if (count($company) > 0) {
$this->form_validation->set_message('company_check', 'Error, The company already exist.');
return false;
} else {
return true;
}
}
)
));
Hope this help,

returning values from one method to another

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

Categories