i get the desired value for first var_dump but get a null value for both the var_dump on submitting the form. can anybody help me with this?
to be precise,i am able to get the desired result for get->trail->id when the form is not submitted,but once i complete the form,and submit it,the value of $id is assigned to be null.
public function trail_cat_cost($trail_unique_code = null)
{
if($this->userlib->isLoggedIn())
{
$code = $trail_unique_code;
$user_id = $this->userlib->getId();
$id = $this->seller_store_model->get_trail_id($code, $user_id);
var_dump($id);
$choice = $this->input->post("travel_cat");
if(is_null($choice))
{
$choice = array();
}
$travel_cat = implode(',', $choice);
$choice1 = $this->input->post("travel_subcat");
if(is_null($choice1))
{
$choice1 = array();
}
$travel_subcat = implode(',', $choice1);
$trail_currency = $this->input->post('trail_currency');
$trail_cost = $this->input->post('trail_cost');
$cost_valid_from = $this->input->post('cost_valid_from');
$cost_valid_upto = $this->input->post('cost_valid_upto');
//$this->form_validation->set_rules('travel_cat', 'Travel Category', 'trim|required');
//$this->form_validation->set_rules('travel_subcat', 'Travel Subcategory', 'trim|required');
$this->form_validation->set_rules('trail_currency', 'Trail Currency', 'trim|required');
$this->form_validation->set_rules('trail_cost', 'Trail Cost', 'trim|required');
$this->form_validation->set_rules('cost_valid_from', 'Cost Valid From', 'trim|required');
$this->form_validation->set_rules('cost_valid_upto', 'Cost Valid Upto', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$this->load->view('trail_cat_cost');
}
else
{
var_dump($id);
$this->seller_store_model->trail_cat_cost($user_id, $id, $travel_cat, $travel_subcat, $trail_currency, $trail_cost, $cost_valid_from, $cost_valid_upto);
echo "success";
//redirect('/seller_store/trail_overview/'.$date);
}
}
else
{
echo "User not authorised";
}
}
Model Code From Comment
public function get_trail_id($code, $user_id) {
$query = $this->db->query("SELECT id FROM trail_basic_info WHERE trail_unique_code = '$code' AND user_id = '$user_id'"); foreach($query->result() as $row) { $id = $row->id; $data = array('trail_id'=>$id); $this->db->update($this->search, $data, array('trail_unique_code'=>$code, 'user_id'=>$user_id)); return $row->id;
}
Related
I don't know what I am doing wrong in this.
If anyone could help!
cause i have tried all solutions...
also undefined variable $data error
/************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->update_student($student_id, $data);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
//***********************Model in CI***//////////////
public function update_student($student_id,$data)
{
$this->db->set($this->table_name,$student_id, $data);
return $this->db->update_id();
}
$data is never defined in the first part of your IF statement.
In particular this line
$data['student'] = $this->stud_model->update_student($student_id, $data);
is the problem. If the form validation is false, you don't want to update the student. Remove that line, and everything should be fine.
Unless you do want to update student even if the validation fails (This is a bad idea, IMO). Then your controller would look like this
public function edit_stud($student_id) {
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name' => $full_name ,
'father_name' => $father_name ,
'roll_no' => $roll_no,
);
$student_id = $this->stud_model->update_student($student_id, $data);
if($this->form_validation->run() === FALSE)
$this->load->view('edit_form' , $data);
} else {
redirect('/stud/edit_stud/'.student_id);
}
}
Thanks for suggestions i have solved the problem i was having
in my code i did some renditions...posting the correct answer for
anyone else, having same sort of problem.
this is the controller code.
/*****controller code*****/
/***************************edit student ******************************/
public function edit_stud($student_id)
{
$this->form_validation->set_rules('full_name', 'full_name', 'required');
$this->form_validation->set_rules('father_name', 'father_name', 'required');
$this->form_validation->set_rules('roll_no', 'roll_no', 'required');
if($this->form_validation->run() === FALSE)
{
$data['student']= $this ->stud_model->get_student($student_id);
$this->load->view('edit_form' , $data);
}
else
{
$full_name = $this->input->post('full_name', true);
$father_name = $this->input->post('father_name', true);
$roll_no = $this->input->post('roll_no', true);
$data = array(
'full_name'=>$full_name ,
'father_name'=>$father_name ,
'roll_no'=>$roll_no,
);
$student_id = $this->stud_model->update_student($student_id,$data);
redirect('/stud/edit_stud/'.student_id);
}
}
/************************delete student ************************/
public function delete_stud($student_id)
{
$this ->stud_model->delete_student($student_id);
redirect('/stud/');
}
/***********************model code *******/
/************to get student id*********/
public function get_student($student_id)
{
$this->db->select('*');
$this->db->from($this->table_name);
$this->db->where('id',$student_id);
$query = $this->db->get();
if($query->num_rows() >0)
{
$return = $query->row();
}
else
{
$return = 0;
}
$query->free_result();
return $return;
}
/*****************update function***********************/
public function update_student($id, $data)
{
$where = array('id' => $id);
$this->db->update($this->table_name, $data, $where);
}
I need help i tried everything but nothing works don't know what's the issue. i want as i check then insert if uncheck then delete but my code doesn't insert
if($this->input->post()){
$select_assigned_ids = $this->input->post('assigned_ids[]');
if ($this->form_validation->run() == FALSE) {
foreach($select_assigned_ids as $tlusers){
$data = array(
'user_id' => $tlusers
);
$test = $this->assign_permission_model->insert($data);
}
}
}else{
//Checkbox is unchecked....
$q = 'Delete from assign_permission ';
$this->section_permission_model->qwr($q);
}
It doesn't insert any value in db
like this code your define array $data remove (,) so insert data
if($this->input->post()){
$select_assigned_ids = $this->input->post('assigned_ids[]');
if ($this->form_validation->run() == FALSE) {
foreach($select_assigned_ids as $tlusers){
$data = array(
'user_id' => $tlusers
);
$test = $this->assign_permission_model->insert($data);
}
}
}else{
//Checkbox is unchecked....
$q = 'Delete from assign_permission ';
$this->section_permission_model->qwr($q);
}
Insert some line code insert data flash maessge
if($this->input->post()){
$select_assigned_ids = $this->input->post('assigned_ids[]');
if ($this->form_validation->run() == FALSE) {
foreach($select_assigned_ids as $tlusers){
$data = array(
'user_id' => $tlusers
);
$test = $this->assign_permission_model->insert($data);
}
$this->session->set_flashdata('msg', '<div id="message" class="alert alert-success"><a class="close" data-dismiss="alert" onclick="self.close()">x</a>Success Messages </div>');
redirect('redirect your page link');
}
}else{
//Checkbox is unchecked....
$q = 'Delete from assign_permission ';
$this->section_permission_model->qwr($q);
}
I have this code:
public function getJccLineItem($id,$action)
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q);
echo $this->db->last_query();
$jccLineItemArray = array();
echo $id;
print_r($res->result());
if($action == 'array')
{
foreach ( $res->result() as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
else
{
$res = $res->result();
}
return $res;
}
The error is in the foreach loop. I have printed the result and it shows the result in object array but when it goes to foreach loop. It show this error
"Call to a member function result() on a non-object "
But when I set db['default']['db_debug']=true , it shows that the $id is missing from the query whereas when it was false it was showing result in object array and giving error at loop. Any Help would be appreciated.Thanks
Controller Code
public function createInvoice( $id = "" )
{
if (empty($id))
{
$id = $this->input->post('dataid');
}
echo $id;
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
} else if ($this->form_validation->run() == TRUE) {
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice', "refresh");
} else {
$this->load->view('admin/viewinvoicesub', $data);
}
}
Try this and let me know if that helps
public function getJccLineItem($id = '' ,$action = '')
{
if($id != '')
{
$res = array();
$q = 'SELECT * FROM jcc_line_items jli,ipo_line_item ili ,line_items li
WHERE jli.line_item_id= ili.id and li.id = jli.line_item_id
and ili.dn_number_id in ( Select dn_number from ipo where project_id= '.$id.')';
$res = $this->db->query($q)->result();
$jccLineItemArray = array();
if($action == 'array')
{
foreach($res as $key => $value) // The error comes in this line
{
$jccLineItemArray[ $value->id ] = $value->item_description;
}
$res = $jccLineItemArray;
}
return $res;
}
else
{
echo "id is null"; die();
}
}
And your Controller code should be
public function createInvoice( $id = "" )
{
$this->load->helper(array('form', 'url'));
$this->load->helper('security');
if ($id = "")
{
$id = (isset($this->input->post('dataid')))?$this->input->post('dataid'):3;// i am sure your error is from here
}
$data['jcc_line_list'] = $this->product_model->getJccLineItem($id,'array');
$data['jcc_line_lists'] = $this->product_model->getJccLineItem($id,'');
$data['items'] = $this->product_model->getAllSubInvoice($id);
$data['single_project'] = $this->product_model->getSingleProject($id);
$data['site'] = $this->product_model->getAllSiteArray();
$data['job_types'] = $this->product_model->getAllJobTypeArray();
$data['title'] = 'Invoice';
$data['operation'] = 'Create';
$data['buttonText'] = 'Save';
$data['id'] = $id;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$this->form_validation->set_rules('line_item_id', 'Line Item', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('job_type_id', 'Job Type', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('site_id', 'Site', 'required|xss_clean|max_length[50]');
$this->form_validation->set_rules('milestone', 'Milestone', 'required|xss_clean|max_length[50]');
$this->form_validation->set_error_delimiters('<span class="error">', '</span>');
if ($this->form_validation->run() === FALSE)
{
$this->session->set_flashdata('error_message', validation_errors());
$this->load->view('admin/viewinvoicesub', $data);
}
else
{
$formData = array(
'invoice_id' => $id,
'line_item_id' => $this->form_validation->set_value('line_item_id'),
'job_type_id' => $this->form_validation->set_value('job_type_id'),
'site_id' => $this->form_validation->set_value('site_id'),
'milestone' => $this->form_validation->set_value('milestone'),
);
$this->product_model->insertInvoiceSub($formData);
$this->session->set_flashdata('sucess_message', "Data successfully save !");
redirect('Products/createInvoice/'.$id, "refresh");
}
}
else
{
$this->load->view('admin/viewinvoicesub', $data);
}
}
I have little knowledge with PHP and I was assigned to try to fix some of the things that don't work in a website. The website basically deals with two different users, a trader who can post articles and a blogger who can post blogs. When a user registers to become a trader and tries to submit an article,the page just redirects to base_url.user/blogger/ instead of base_url.user/trader/. I think this is because it isn't recognizing the user as a trader. Can you please look at the codes? If you have any ideas as to why it wouldn't work I'm open to ideas
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Index Page for this controller.
*
* Since this controller is set as the default controller in
* config/routes.php, it's displayed
*
*
* File Controller; location: application/controllers/admin.php
* Author : Pradeep
* Date : Sunday Feb 5th, 2012
**/
class Register extends CI_Controller {
private $user;
private $logData;
function _Register()
{
parent::controller();
$this->config->load('constants.php');
}
public function blogger()
{
//-------------------------SENDING ERROR MESSAGE FOR LOGIN-------------------
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Blogger';
$this->load->view('register-blogger',$data);
}
public function trader()
{
$data['captchaError'] = '';
$data['captcha'] = $this->getCaptcha();
$data['pageTitle']='Registration | Trader';
$this->load->view('register-trader',$data);
}
public function activate()
{
$data['pageTitle']='Registration | Succesfully registered';
$this->load->view('register-success',$data);
}
public function process()
{
$date = date('Y-m-d');
$userid = uniqid();
$captchaError = '';
if($this->input->post('Submit'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('mycheck[]', 'Buyer or Supplier','required');
$this->form_validation->set_rules('material[]', 'materials','required');
$this->form_validation->set_rules('company', 'Company name', 'required');
$this->form_validation->set_rules('cname', 'Contact name','required');
$this->form_validation->set_rules('cemail', 'Contact email', 'required|valid_email');
$this->form_validation->set_rules('nation', 'Country', 'required');
$this->form_validation->set_rules('city', 'City','required');
$this->form_validation->set_rules('fax');
$this->form_validation->set_rules('mobile');
$this->form_validation->set_rules('phone');
$this->form_validation->set_rules('website');
$this->form_validation->set_rules('address');
$this->form_validation->set_rules('zip');
$this->form_validation->set_rules('content', 'Tell something about urself', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-trader',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
if($this->input->post('material'))
{
$material = '';
foreach($this->input->post('material') as $value)
{
$material.= $value.',';
}
$material = rtrim($material,',');
}
$mycheck = $this->input->post('mycheck');
$mycheckOne = '';
$mycheckTwo = '';
if(!empty($mycheck[0])){$mycheckOne = $mycheck[0];}
if(!empty($mycheck[1])){$mycheckTwo = $mycheck[1];}
$config['file_name'] = uniqid();
$config['upload_path'] = UP_PATH;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile1'))
{
$error = $this->upload->display_errors();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('name'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
else
{
$data = array('upload_data' => $this->upload->data());
$filepath = $data['upload_data']['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = UP_PATH.$filepath;
$config['new_image'] = UP_PATH.'thumbs/';
$config['create_thumb'] = TRUE;
$config['thumb_marker'] = '';
$config['maintain_ratio'] = TRUE;
$config['width'] = 75;
$config['height'] = 50;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = array(
'supplier'=>$mycheckOne,
'buyer'=>$mycheckTwo,
'title'=>$this->input->post('company'),
'cname'=>$this->input->post('cname'),
'material'=>$material,
'email'=>$this->input->post('email'),
'phone'=>$this->input->post('phone'),
'fax'=>$this->input->post('fax'),
'mobile'=>$this->input->post('mobile'),
'web'=>$this->input->post('website'),
'country'=>$this->input->post('nation'),
'city'=>$this->input->post('city'),
'address'=>$this->input->post('address'),
'zip'=>$this->input->post('zip'),
'content'=>$this->input->post('content'),
'image'=>$filepath,
'date'=>$date,
'userid'=>$userid,
'status'=>0
);
}
$this->db->insert(TBL_CLA,$data);
$log_type = 'trader';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>1
);
$this->db->insert(TBL_USE,$dataOne);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
if($this->input->post('Login'))
{
//---------------------------------FORM VALIDATION STARTS HERE---------------------------------
$this->form_validation->set_error_delimiters('', '');
$this->form_validation->set_rules('fname', 'Full name','required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[tbl_user.email]');
$this->form_validation->set_rules('password', 'password', 'trim|required|min_length[6]|matches[cpassword]');
$this->form_validation->set_rules('cpassword', 'Password confirmation', 'required');
$this->form_validation->set_rules('captchaText', 'captcha text', 'required');
//-----------------------------------FORM VALIDATION ENDS HERE--------------------------------------
//------------------------------------CAPTCHA CHECK------------------------------------------
if($this->input->post('captchaText'))
{
$expiration = time()-7200; // Two hour limit
$this->db->query("DELETE FROM captcha WHERE captcha_time < ".$expiration);
// Then see if a captcha exists:
$sql = "SELECT COUNT(*) AS count FROM captcha WHERE word = ? AND ip_address = ? AND captcha_time > ?";
$binds = array($_POST['captchaText'], $this->input->ip_address(), $expiration);
$query = $this->db->query($sql, $binds);
$row = $query->row();
if ($row->count == 0)
{
$captchaError = "You must submit the word that appears in the image";
}
}
//--------------------------------------CAPTCHA CHECK ENDS HERE----------------------------
//----------------------------------FORM VALIDATION RETURN ERRORS---------------------------
if ($this->form_validation->run() == FALSE || $captchaError!='')
{
$data['captcha'] = $this->getCaptcha();
$data['captchaError'] = $captchaError;
$data['pageTitle']='Registration | Error';
$this->load->view('register-blogger',$data);
}
//-----------------------------------------------END---------------------------------------
//---------------------------------------INSERT DATA INTO DATABASE-----------------------
else
{
$date = date('Y-m-d');
$log_type = 'blogger';
$password = do_hash($this->input->post('password'));
$dataOne = array(
'password'=>$this->security->xss_clean($password),
'fname'=>$this->security->xss_clean($this->input->post('fname')),
'email'=>$this->security->xss_clean($this->input->post('email')),
'log_type'=>$log_type,
'userid'=>$userid,
'status'=>0,
'date'=>$date,
'active'=>0
);
$this->db->insert(TBL_USE,$dataOne);
$data['link'] = 'http://www.arabrecycling.org/activate/created/'.$userid;
$data['name'] = $this->input->post('fname');
$message = $this->load->view('includes/activate',$data, TRUE);
$subject = 'Account Activation';
$fromTest = 'The Arab Recycling Initiative';
$this->userRegEmail('info#arabrecycling.org',$this->input->post('email'),$message,$subject,$fromTest);
$this->session->set_userdata('fname', $this->input->post('fname'));
redirect(base_url().'register/activate');
}
}
}
//-------------------------------------------------------CAPTCHA CREATION STARTS HERE------------------------
public function getCaptcha(){
$this->load->library('common');
$this->common = new common();
$this->load->helper('captcha');
$vals = array(
'word' => $this->common->GetRandomCaptchaText(8),
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'font_path' => base_url().'system/fonts/Candice.ttf',
'img_width' => '150',
'img_height' => 30,
'expiration' => 7200
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$query = $this->db->insert_string('captcha', $data);
$this->db->query($query);
return $cap['image'];
}
//--------------------------------------------------------CAPTCHA CREATION ENDS HERE------------------------------------------------
//--------------------------------------------------------CONFIGURING EMAIL------------------------------------------------
public function userRegEmail($from,$to,$message,$subject,$fromTest){
$email_config['protocol'] = 'mail';
$email_config['mailtype'] = 'html';
$this->email->initialize($email_config);
$this->email->from($from, $fromTest);
$this->email->to($to);
$this->email->subject($subject);
$this->email->message($message);
$this->email->send();
}
//--------------------------------------------------------EMAIL CONFIGURATION ENDS HERE------------------------------------------------
Use SESSIONS:
On top of your page set:
<?php
//Check if session has not been started.
if (session_status() == PHP_SESSION_NONE)
{
session_start();
}
?>
In the code when defining a trader or blogger:
$_SESSION['USER'] = "trader";
or
$_SESSION['USER'] = "blogger";
Then you can execute the code you want:
//If it has not been set, do trader by default.
if (!ISSET($_SESSION['USER'])
{
$_SESSION['USER'] = "trader";
}
if ($_SESSION['USER'] == "blogger")
{
//Execute code for blogger
}
else if($_SESSION['USER'] == "trader")
{
//Execute code for trader
}
Sessions are stored in your browser as long as your "Page/Session" is open. Those "Variables" are user specific.
Hope this helps :)
You should identify if a user is a trader or a blogger, and then set appropriate session variables accordingly. A simple if statement to check which is logged in depending on which session variable is set should do the trick? If i'm understanding your question correctly.
What I would suggest (it will probably be easier) is
1. add an attribute to your user table in your database that is Account_Type enum('trader','blogger') not null.
2. Add radio buttons to your form when they sign up to choose if they are a trader or blogger
and obviously have this data sent back to your database
3. When they Login (i'm assuming all users have a unique username) do something like
-Set Session variables to 0
$_SESSION['trader'] = 0;
$_SESSION['blogger'] = 0;
-find username in database and for that username check if trader or blogger.
//A Query to find the Account_type that goes with the input account
$accquery = "SELECT Account_type FROM Account WHERE Account_Name =$_POST['account']";
//Running the query
$result = mysqli_query($connect,$accquery);
//Using an array to fetch the type and put it into a variables place
while($row = mysqli_fetch_array($connect,$result))
{
$acctype = $row['Account_Type'];
}
else {
die("Query failed");
}
And then do something like
if($acctype == "trader") {
$_SESSION['trader'] = 1;
elseif($acctype == "Blogger") {
$_SESSION['blogger'] =1;
else {
//error message
}
and then when you need to check which they are you can do something like
if((isset($_SESSION['trader'])) && ($_SESSION['trader'] == "1")){
//specific code for trader
}
and you can apply the same for blogger.
I would also advise you look into sanitizing your inputs, it's simple but very important.
Also note, do a thorough search through stackoverflow for answers to your questions because more than likely you will find something.
-Hope this helps, note its only rough so you will have to work around it but you should have some grasp of PHP anyways so that should do.
I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');