Not able to insert the data inside db - php

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

Related

Codeigniter Call to a member function result() on a non-object

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

null value for var_dump

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

PHP Help, not recognizing the different users

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.

Codeigniter get all rows from db

I'm working on task manager where have 2 types of user: Administrators(all privileges), and Users(limited privileges).
Here's my task function in controller
function task($id) {
$data = array(
'query' => $this->main_model->get_task($id),
'task_id' => $id,
);
$data2['comments'] = $this->main_model->get_comments($id);
$this->load->library('form_validation');
$this->load->helper('security');
$this->form_validation->set_rules('comment_text', 'comment_text', 'trim|required|strip_tags|xss_clean');
if ($this->form_validation->run() === FALSE)
{
if($this->main_model->get_task($id))
{
foreach ($this->main_model->get_task($id) as $tas)
{
$data = array(
'title' => $tas->task_name,
'desc' => $tas->task_description,
'date_created' => $tas->date,
'date_started' => $tas->task_start_date,
'deadline' => $tas->task_deadline,
'creator' => $tas->task_creator,
'owner' => $tas->task_owner,
'attach'=>$tas->attachment_name,
'status'=>$tas->task_status,
'priority'=>$tas->task_priority,
'task_id'=>$tas->ID_task,
'base_url' => base_url()
);
}
$data1 = array(
'emps' => $this->main_model->get_employees(),
'creator' => $this->main_model->get_details($id),
'owner' => $this->main_model->get_owner($id)
);
if ($this->session->userdata('employee_type') == 3) {
$qu = $this->main_model->permission();
$id = $this->session->userdata('id');
$id_emp = $this->uri->segment(3);
//foreach ($qu as $q) {
if (in_array($id, $qu[0]) && in_array($id_emp, $qu[0])) {
$this->load->view('task', array_merge($data, $data1, $data2));
}
else {
echo "No Permission to access this task";
}
}
}
}
else
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf|txt|text|rtf|jpg|gif|png';
$config['max_size'] = '1024';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
if ("You did not select a file to upload." != $this->upload->display_errors('','')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('task', $error);
}
else {
$this->main_model->set_comments($id);
redirect(current_url());
}
}
else {
$data = array('upload_data' => $this->upload->data());
$data1 = $this->upload->data();
$data2 = $data1['file_name'];
$this->main_model->set_comments($id);
$this->main_model->set_attachment($id, $data2);
redirect(current_url());
}
}
}
and my permission function in model:
function permission() {
$query = $this->db->get('employees_tasks');
$ret = $query->result_array();
return $ret;
}
What I'm trying to do is, get all data from database employee_tasks check if the ID_task and ID_employee are in the same row in database, but I can't get it working, I only getting first row of database, not the others, and that's my key problem, get all rows from db.
I tried query database with result, result_array, row, row_array, but for some reason everything is listing only first row in db. Any Help would be appreciated.
To get all results from a separate table using codeigniter Active record you can do like this
function permission() {
$this->db->select("*");
$this->db->from("employees_tasks");
$this->db->where('id', 'your id');
$query = $this->db->get();
return $query->result();
// OR
$query = $this->db->query("SELECT * from employees_tasks WHERE your condition");
return $query->result();
}
Hope it makes sense

Form validation error-Call to undefined method CI_Form_validation::set_fields() in php codeigniter

When i try to update the query in php- codeigniter I get this form_validation error. Here is my Controller
THIS gives me error and I am not able to update or add an entry into my database
<?php
class Person extends CI_Controller {
// num of records per page
private $limit = 15;
function Person() {
parent::__construct();
//$this->load->library('table','form_validation');
$this->load->library('table');
$this->load->library('form_validation');
$this->form_validation->set_rules();
$this->load->helper('url');
$this->load->model('personModel', '', TRUE);
}
function index($offset = 0) {
$uri_segment = 3;
$offset = $this->uri->segment($uri_segment);
// load data
$persons = $this->personModel->get_paged_list($this->limit, $offset)->result();
// have pagntn
$this->load->library('pagination');
$config['base_url'] = site_url('person/index/');
$config['total_rows'] = $this->personModel->count_all();
$config['per_page'] = $this->limit;
$config['uri_segment'] = $uri_segment;
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
// generate table data
$this->load->library('table');
$this->table->set_empty(" ");
$this->table->set_heading('No', 'Name', 'Gender', 'Education',
'Date of Birth (dd-mm- yyyy)', 'Interest', 'Actions');
$i = 0 + $offset;
foreach ($persons as $person) {
$this->table->add_row(++$i, $person->name, strtoupper($person->gender) ==
'M' ? 'Male' : 'Female', ($person->education),
date('d-m-Y', strtotime($person->dob)), ($person->interest),
anchor('person/view/' . $person->id, 'view', array('class' => 'view',
'onclick' => "return confirm('View Full Details?')")) . ' ' .
anchor('person/update/' . $person->id, 'update', array('class' => 'update')) . ' ' .
anchor('person/delete/' . $person->id, 'delete', array('class' =>
'delete', 'onclick' => "return confirm('Are you sure want to delete this person?')"))
);
}
$data['table'] = $this->table->generate();
$this->load->library('table');
$this->load->library('form_validation');
// load view
$this->load->view('personList', $data);
}
function add() {
// set validation propert/ies
$this->set_fields();
// set common properties
$data['title'] = 'Add new person';
$data['message'] = '';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function addPerson() {
// set common properties
$data['title'] = 'Add new person';
$data['action'] = site_url('person/addPerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))));
$id = $this->personModel->save($person);
// set form input name="id"
$this->form_validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function view($id) {
// set common properties
$data['title'] = 'Person Details';
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// get person details
$data['person'] = $this->personModel->get_by_id($id)->row();
// load view
$this->load->view('personView', $data);
}
function update($id) {
// set validation properties
$this->set_fields();
// prefill form values
$person = $this->personModel->get_by_id($id)->row();
$this->form_validation->id = $id;
$this->form_validation->name = $person->name;
$_POST['gender'] = strtoupper($person->gender);
$this->form_validation->dob = date('d-m-Y', strtotime($person->dob));
// set common properties
$data['title'] = 'Update person';
$data['message'] = '';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// load view
$this->load->view('personEdit', $data);
}
function updatePerson() {
// set common properties
$data['title'] = 'Update person';
$data['action'] = site_url('person/updatePerson');
$data['link_back'] = anchor('person/index/', 'Back to list of persons',
array('class' => 'back'));
// set validation properties
$this->set_fields();
$this->set_rules();
// run validation
if ($this->form_validation->run() == FALSE) {
$data['message'] = '';
} else {
// save data
$id = $this->input->post('id');
$person = array('name' => $this->input->post('name'),
'gender' => $this->input->post('gender'),
'dob' => date('Y-m-d', strtotime($this->input->post('dob'))),
'education'=>$this->input->post('education'),
'interest'=>$this->input->post('interest'));
$this->personModel->update($id, $person);
// set user message
$data['message'] = '<div class="success">update person success</div>';
}
// load view
$this->load->view('personEdit', $data);
}
function delete($id) {
// delete person
$this->personModel->delete($id);
// redirect to person list page
redirect('person/index/', 'refresh');
}
// validation fields
function set_fields() {
$fields['id'] = 'id';
$fields['name'] = 'name';
$fields['gender'] = 'gender';
$fields['dob'] = 'dob';
$fields['education']='educaiton';
$fields['interest']='
$this->form_validation->set_fields('$fields');
//echo"hellofff";
//exit;
}
// validation rules
function set_rules() {
$rules['name'] = 'trim|required';
$rules['gender'] = 'trim|required';
$rules['dob'] = 'trim|required|callback_valid_date';
$rules['education']='trim|required';
$rules['interest']='trim|required';
$this->form_validation->set_rules($rules);
$this->form_validation->set_message('required', '* required');
$this->form_validation->set_message('isset', '* required');
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
}
function form_validation() {
$this->add();
}
// date_validation callback
function valid_date($str) {
if (!ereg("^(0[1-9]|1[0-9]|2[0-9]|3[01])-(0[1-9]|1[012])-([0-9]{4})$", $str)) {
$this->form_validation->set_message('valid_date', 'date format is not
valid. dd-mm-yyyy');
return false;
} else {
return true;
}
}
}
?>
This is my model:
PersonMOdel: Database name is employeeregistration and tableused is tbl_person
<?php
class PersonModel extends CI_Model {
// table name
private $tbl_person= 'tbl_person';
function Person(){
parent::construct();
}
// get number of persons in database
function count_all(){
return $this->db->count_all($this->tbl_person);
}
// get persons with paging
function get_paged_list($limit = 15, $offset = 0){
$this->db->order_by('id','asc');
return $this->db->get($this->tbl_person, $limit, $offset);
}
// get person by id
function get_by_id($id){
$this->db->where('id', $id);
return $this->db->get($this->tbl_person);
}
// add new person
function save($person){
$this->db->insert($this->tbl_person, $person);
return $this->db->insert_id();
}
// update person by id
function update($id, $person){
$this->db->where('id', $id);
$this->db->update($this->tbl_person, $person);
}
// delete person by id
function delete($id){
$this->db->where('id', $id);
$this->db->delete($this->tbl_person);
}
}
?>
This can be cossidered a CRUD application.

Categories