Insert to db in an iterative way - php

I want to insert to my database payment table that should be done in this way.
The payment table that I have includes both group_id and member_id as a foreign key related to the table groups and member respectively.
What I want to do is once I hit the button "Pay" it should insert for each and every member_id as a row in the payment table.
Here is my code..
In my controller I have
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$this->load->model('Member_model');
$memberid = $this->Member_model->paymember();
foreach ($memberid->result_array() as $id){
$memberid[] = $id;
$data = array(
'group_id' => $this->input->post('group_id',TRUE),
'member_id' => $memberid,
'paid_by' => $this->input->post('paid_by',TRUE),
'from_date' => $this->input->post('from_date',TRUE),
'to_date' => $this->input->post('to_date',TRUE),
'amount' => $this->input->post('amount',TRUE),
'reference_number' => $this->input->post('reference_number',TRUE),
//'last_updated_by' => $this->input->post('last_updated_by',TRUE),
//'last_update_time' => $this->input->post('last_update_time',TRUE),
);
}
$this->Payment_model->insert($data);
$this->session->set_flashdata('message', 'Record Created Successfully!');
redirect(site_url('payment'));
}
}
And in my model which is the Member_model I've included in the controller..
function paymember(){
$data= array();
$this->db->where('group_id',$this->input->post('group_id'));
$memberid = $this->db->get('member');
if ($memberid->num_rows() > 0) {
foreach ($memberid->result_array() as $row){
$data[] = $row;
}
}
}
Please help me out. Thank you.

Now I've solved the problem.
In my controller there I have got the array value from the model...
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$this->load->model('Member_model');
$memberid = $this->Member_model->paymember();
if (count($memberid)) {
foreach ($memberid as $id) {
$data = array(
'group_id' => $this->input->post('group_id',TRUE),
'member_id' => $id,
'paid_by' => $this->input->post('paid_by',TRUE),
'from_date' => $this->input->post('from_date',TRUE),
'to_date' => $this->input->post('to_date',TRUE),
'amount' => $this->input->post('amount',TRUE),
'reference_number' => $this->input->post('reference_number',TRUE),
'last_updated_by' => $this->session->userdata('username'),
//'last_update_time' => $this->input->post('last_update_time',TRUE),
);
$this->Payment_model->insert($data);
echo $data;
}
}
$this->session->set_flashdata('message', 'Record Created Successfully!');
redirect(site_url('payment'));
}
}
Also on my previous model paymember method there was a problem which its not returning any result so I've fixed that with this code....
function paymember(){
$data= array();
$this->db->where('group_id',$this->input->post('group_id'));
$query = $this->db->get('member');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row['member_id'];
}
}
$query->free_result();
return $data;
}
Thank you for ur support!

Related

update query not updating table in transactions

I m trying to get and update data at same time but after getting data transaction is rolled back, because table is not updating.
Controller -
public function addAmount()
{
$this->form_validation->set_rules('balance_id', 'Balance Id', 'required|trim');
$this->form_validation->set_rules('farmer_id', 'farmer_id', 'required|trim');
$this->form_validation->set_rules('amount', 'amount', 'required|trim');
$this->form_validation->set_rules('amount_discount', 'discount', 'required|trim');
$this->form_validation->set_rules('payment_mode', 'payment mode', 'required|trim');
if ($this->form_validation->run() == false) {
$data = array(
'amount' => form_error('amount'),
'balance_id' => form_error('balance_id'),
'farmer_id' => form_error('farmer_id'),
'amount_discount' => form_error('amount_discount'),
'payment_mode' => form_error('payment_mode'),
);
$array = array('status' => 'fail', 'error' => $data);
echo json_encode($array);
} else {
$id =$this->generate_otp();
$data = array(
'farmer_id' => $this->input->post('farmer_id'),
'balance_id' => $this->input->post('balance_id'),
'amount_paid' => $this->input->post('amount'),
'paying_date' => $this->input->post('date'),
'amount_discount' => $this->input->post('amount_discount'),
'description' => $this->input->post('description'),
'payment_mode' => $this->input->post('payment_mode'),
'payment_id' =>$id,
);
$inserted_id = $this->advance_model->amount_deposit($data);
echo '<pre>'; print_r($inserted_id); echo ("</pre>"); exit();
$array = array('status' => 'success', 'error' => '');
echo json_encode($array);
}
}
Model:
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
return $query->row();
if(!empty($query)){
$b =$query['balance'];
$balance =$b - $paid_amount;
}
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}
When amount to be added the balance amount need to be update automatically, but now transaction is roll back because not able to update balance amount after getting it from same table, thanks in advance.
Just added foreach loop and removed return statement now it's working fine.
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
$result = $query->result();
}
if (!empty($result) && isset($result)) {
foreach ($result as $key => $balance_value) {
$balance_id = $balance_value->balance_id;
$balanceAmount = $balance_value->balance;
$balance = $balanceAmount - $paid_amount;
}
$this->db->where('balance_id', $balance_id);
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}

getting multiple customer details In codeigniter

i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}

How to Update Two table Data one after other In codeigniter?

how to update plan with vendor_plan_task_status_mapp table.
the model for plan update is
public function updatePlanData(){
$planId = $this->input->post('plan_id');
$data = array(
'plan_title' => $this->input->post('plan_title'),
'plan_price' => $this->input->post('plan_price'),
'plan_desc' => $this->input->post('plan_desc')
);
$this->db->where('plan_id', $planId);
$this->db->update('tbl_plan', $data);
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
foreach ($this->input->post('task_id') as $key => $value)
{
$data2 = array(
'plan_id' => $planId,
'task_id' => $value
);
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
//-------- HEAR I NEED A CODE TO UPDATE The V_T_S_M table-----------
}
after 1st table update i want to update the data in vendr_task_status_mapping table?????
IN THIS ANSWER YOU GET AN ERROR IF YOU CHANGE THE PLAN BUT USING THIS CODE YOU HAVE TO SIMPLY EDIT AND UPDATE IT ANGIN AND THIS MODEL IS CREATE A NEW ID FOR YOUR TASK AND INSERT IT AGAIN.
public function vendorUpdateModel($data)
{
$vendor_id = $this->input->post('vendor_id');
$data = array(
'category_id' => $this->input->post('category_id'),
'plan_id' => $this->input->post('plan_id'),
'city_id' => $this->input->post('city_id'),
'business_name' => $this->input->post('business_name'),
'owner_name' => $this->input->post('owner_name'),
'contact_no1' => $this->input->post('contact_no1'),
'contact_no2' => $this->input->post('contact_no2'),
'vendor_email' => $this->input->post('vendor_email'),
'subscription_date' => $this->input->post('subscription_date'),
'vendor_description' => $this->input->post('vendor_description'),
'vendor_address' => $this->input->post('vendor_address')
);
$this->db->where('vendor_id', $vendor_id);
$this->db->update('vendor',$data);
$this->db->where('vendor_id',$vendor_id);
$this->db->delete('vendor_task_status_mapping');
$this->db->select('task_mapp_id');
$this->db->where('plan_id',$this->input->post('plan_id'));
$query = $this->db->get('plan_task_mapping');
foreach($query->result() as $row)
{
$data2 = array(
'task_mapp_id' => $row->task_mapp_id,
'vendor_id' => $vendor_id,
'task_status' => '0'
);
$this->db->insert('vendor_task_status_mapping', $data2);
}
return;
}
If you added one field in plan_task_mapping table for add unique number then... As you mention your code:
$unique=array();
foreach ($this->input->post('task_id') as $key => $value)
{
$no=rand(0, 15);
$data2 = array(
'unique_no'=>$no,
'plan_id' => $planId,
'task_id' => $value
);
$unique[] = $no; //store no in array to use it.
// echo "Index {$key}'s value is {$value}.";
$this->db->insert('plan_task_mapping', $data2);
}
Before deleting plan_task_mapping table data. fetch that data.
function select()
{
$this->db->where('plan_id',$planId);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row)
{
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
Then delete the data as you mention in you code:
$this->db->where('plan_id',$planId);
$this->db->delete('plan_task_mapping');
Then delete that old data from VTSM table:
$this->db->where('vendor_plan_task_mapping_id',$data[0]['id']); //this data[0]['id'] come form select(). change field name if required.
$this->db->delete('VTSM');
Here fetch that new inserted data by that unique no: //which we stored it in array.
foreach($unique as $u_no)
{
$this->db->where('unique_no',$u_no);
$Q = $this->db->get('plan_task_mapping');
if($Q->num_rows() > 0)
{
foreach ($Q->result_array() as $row1)
{
$plan[] = $row1;
}
}
$Q->free_result();
return $plan;
}
In above code we have fetched that new inserted data to get their id to insert status.
Now inserting status:
foreach($plan as $a)
{
$Sdata=array(
"plan_task_mapping_id"=>$a['id'], //this is new id change name if required
"status"="your new status");
$this->db->insert('VTSM',$Sdata);
}
Use $this->db->insert_batch(); instead of inserting in foreach loop.
Check at this link how to use it.

How to create multiple conditioner login in codeigniter

my model is here.....but i need to select status of admin ....... but
i m new in codeigniter....and don't no how to select... my need is...
select admin whole detail from table on condition admin status =
active and id=1...
my model is :
public function login($value) {
$query = $this->db->get_where('tbl_admin', $value, 1, 'active');
if ($query->num_rows() > 0) {
$row = $query->row_array();
$sess_arr = array(
'admin_user' => $row['fld_admin_username'],
'adm_key' => $row['fld_admin_key'],
'admin_type' => $row['fld_admin_type'],
'admin_id' => $row['fld_admin_id'],
'admin_logged_in' => TRUE
);
$this->session->set_userdata($sess_arr);
//echo "<pre>";print_r($this->session->all_userdata());exit;
}
else{
$this->session->set_flashdata('error', 'Invalid username/password');
redirect('adminzone');
}
}
The correct syntax for the first line would be:
$query = $this->db->get_where('tbl_admin', array('id' => 1, 'status' => 'active'));
I.e. The second parameter to get_where is an associative array of fields and their values..
Edit: Or perhaps it should be
$query = $this->db->get_where('tbl_admin', array('id' => $value, 'status' => 'active'));
(I am not sure what the $value variable is for here).

Issue with saving an update information in Codeigniter

My goal is to update job_contract.
There are two ways that this SHOULD be done. 1. through the client's page AND 2. through the provider's page.
What I currently have is in my job model is:
public function update_job_contract($post_obj)
{
$id = $post_obj['id'];
$data = array
(
'client_feedback' => $post_obj['client_feedback'],
'client_notetoself' => $post_obj['client_notetoself'],
'contract_status' => $post_obj['contract_status'],
'client_id' => $this->auth_model->get_user_id()
);
$this->db->insert('job', $data);
}
public function provider_update_job_contract($post_obj)
{
$id = $post_obj['id'];
$data = array
(
'provider_feedback' => $post_obj['provider_feedback'],
'provider_notetoself' => $post_obj['provider_notetoself'],
'provider_id' => $this->auth_model->get_user_id()
);
$this->db->insert('job', $data);
}
I have the following lines in my client controller page:
public function update_job_contract()
{
$this->validateRole('client');
$this->load->model('job_model');
$id = $this->uri->segment(3,0);
$data['job'] = $this->job_model->get_job($id);
$this->load->view('client/update_job_contract', $data);
}
public function update_job_contract_submit()
{
$this->validateRole('client');
$this->load->model('job_model');
if ( '0' == $_POST['id'] ) {
$this->job_model->update_job_contract($_POST);
//}
redirect('client/manage_job_contracts?message=Congratulations!');
}
And this in my provider controller page:
public function provider_update_job_contract()
{
$this->validateRole('provider');
$this->load->model('job_model');
$id = $this->uri->segment(3,0);
$data['job'] = $this->job_model->get_job($id);
$this->load->view('provider/provider_update_job_contract', $data);
}
public function provider_update_job_contract_submit()
{
$this->validateRole('provider');
$this->load->model('job_model');
if ( '0' == $_POST['id'] ) {
$this->job_model->provider_update_job_contract($_POST);
}
redirect('provider/job_contracts?message=Congratulations!');
}
Problem is, they don't really update the entries. Please help..
You are using $this->db->insert(), but with Active Record to update the row you should be using $this->db->update()
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', $id);
$this->db->update('mytable', $data);
Another words your functions should look like this:
public function update_job_contract($post_obj)
{
$id = $post_obj['id'];
$data = array
(
'client_feedback' => $post_obj['client_feedback'],
'client_notetoself' => $post_obj['client_notetoself'],
'contract_status' => $post_obj['contract_status'],
'client_id' => $this->auth_model->get_user_id()
);
$this->db->where('id', $id);
$this->db->update('job', $data);
}
public function provider_update_job_contract($post_obj)
{
$id = $post_obj['id'];
$data = array
(
'provider_feedback' => $post_obj['provider_feedback'],
'provider_notetoself' => $post_obj['provider_notetoself'],
'provider_id' => $this->auth_model->get_user_id()
);
$this->db->where('id', $id);
$this->db->update('job', $data);
}
Also, inside the controllers $_POST should be replaced with $this->input->post()
Using this one as example:
public function provider_update_job_contract_submit()
{
$this->validateRole('provider');
$this->load->model('job_model');
$post = $this->input->post();
if ( '0' == $post['id'] )
{
$this->job_model->provider_update_job_contract($post);
}
redirect('provider/job_contracts?message=Congratulations!');
}
Make sure you update other controllers in the same way

Categories