how to take the auto increment value to post.
here I insert two tables successfully, I create a condition after insertion, then update the data.
I have two tables, the first 'service' table and the second table 'customer_address'
customer_address table, has id_address as autoincrement.
when inserting data into two tables, I want to get the value id_address in the customer_address table. to be updated to the 'service' table.
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
//'id_alamat' => this autoincrement
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db-> select('id_alamat')-> from('customer_address')->where('id_kota', $kot)->get()-> result();
foreach($sheet as $value) {
$hsl = array(
'id_muat' => $value - > id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
when I updated the 'service' table I updated everything. how to update based on the data input only?
You must send id_alamat from view to your controller and make a unique code not just using autoincrement.
for example:
public function import () {
include APPPATH.
'third_party/PHPExcel/PHPExcel.php';
$excelreader = new PHPExcel_Reader_Excel2007();
$loadexcel = $excelreader-> load('excel/'.$this-> filename.
'.xlsx'); //here I am loading data from an excel file for import
$sheet = $loadexcel->getActiveSheet()->toArray(null, true, true, true);
$data = array();
$numrow = 1;
foreach($sheet as $row) {
$a['acak'] = $this-> M_order-> bikin_kode();
$resi = $a['acak'];
$key1 = $this-> M_order-> db_cek($row['C']);
$origin = $key1['id_origin'];
if ($numrow > 1) {
array_push($data, array(
'tracking_number' => $resi,
'id_cs' => $row['B'],
'id_origin' => $origin,
'id_muat' => $row['D'],
));
$datax = array(
'id_alamat' => $row['id_alamat'],
'id_cs' => $row['AM'],
'nama' => $row['AN'],
);
$this->db-> insert('customer_address', $datax);
// this update data to table service //
//here I am looping, to retrieve the address_id which was just at POST,
$isi = $this->db->select('id_alamat')->from('customer_address')->where('id_kota', $kot)->get()-> result();
//change $sheet to $isi
foreach($isi as $value) {
$hsl = array(
'id_muat' => $value->id_alamat,
);
$this->db->update('service', $hsl);
}
}
$numrow++;
}
$this->M_order->insert_multiple($data); //to table service
}
Related
I want to make function that update client.client_status data from given $id parameters from controller end function that fetched from booking.booking_id
Here my controller
function end($book_id = null) {
if (!empty($book_id)) {
// Booking Table
$table = 'booking';
$where = [
'book_id' => $book_id,
];
$data = [
'room_status' => 1,
];
$this->Model_Data->booking_update($table, $where, $data);
// Client Table
$table = 'client';
$client_id = $???????; // How to get booking.client_id from given id parameters
$where = [
'client_id' => $client_id,
];
$data = [
'room_status' => 1,
];
$this->Model_Data->booking_update($table, $where, $data);
$this->session->set_flashdata('book_ended', 'Book Ended');
redirect('book');
}
else {
$this->session->set_flashdata('book_end_error', 'Book End Error');
redirect('book');
}
}
Here my SQL Tables
According to your comment in Question , book_by_client_id is equal to client_id then for :
Accessing a single row:
(1) Result as an Object
$data_result = $this->db->get_where('booking',array('book_id'=>$book_id ))->row();
$book_by_client_id =$data_result->book_by_client_id;
$client_id = $book_by_client_id; // client_id
(2) Result as an Array
$data_result = $this->db->get_where('booking',array('book_id'=>$book_id ))->row_array();
$book_by_client_id =$data_result['book_by_client_id'];
$client_id = $book_by_client_id; // client_id
Note : for more info about row(); && row_array();
https://codeigniter.com/userguide3/database/results.html#result-rows
i have 1 million data using foreach.
ex table:
table
the data
data
i want to inserting that's data using batch/multipleinsert, but i have problem when i got duplicate data. if data duplicate i want the field amount will sum and update amount field with sum amount duplicated data.
this is my code before
<?php
foreach ($data_transaksi as $key)
{
if($key['STATUS_COA'] != $key['CHART_OF_ACCOUNT_STATUS'])
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2);
}
else
{
$amount = round($key['AMOUNT'],2) *-1;
}
}
else
{
if($key['ACCOUNT_CATEGORY_CODE'] == '9')
{
$amount = round($key['AMOUNT'],2)*-1;
}
else
{
$amount = round($key['AMOUNT'],2);
}
}
$dt_exsis = $this->ledger_model->cek_data_coa_exsis($key['COA_CODE'],$modul,$ID_USER);
if(empty($dt_exsis['id']))
{
//TRYINSERTINGBATCH
// $datainsert[] = '('.$key['COA_CODE'].','.$amount.','.$ID_USER.',"'.$modul.'")';
// $test = $key['COA_CODE'];
$datainput = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
$this->ledger_model->save_rows_to_table($datainput,'finance_lapkue_temp');
}
else
{
$amount_fix = $amount + $dt_exsis['AMOUNT'];
$data=array(
'AMOUNT' => $amount_fix
);
$this->ledger_model->edit_rows_to_table_where($data,'finance_lapkue_temp','id',$dt_exsis['id']);
// $q = "UPDATE finance_lapkue_temp set AMOUNT = '$amount_fix' where id = '".$dt_exsis['id']."'";
// $this->db->query($q);
}
// $data_amount[$key['COA_CODE']] += $amount;
}
?>
if i using this code, the proccess so slow
Good option will to pass only data to DB that you want to insert. All the data cleaning task can be done in controller.
// Create a data array and add all info
$data = [];
//if user does not exist add it in array
if (empty($dt_exist($id))) {
$data[$ID_USER] = array(
'COA_CODE' => $key['COA_CODE'],
'AMOUNT' => $amount,
'MODUL' => $modul,
'USER_ID' => $ID_USER
);
}
else {
//if user exist in $data just modify the amount
if (!empty($data[$ID_USER])) {
$data[$ID_USER]['AMOUNT'] += $dt_exsis['AMOUNT'];
}
else {
// if user does not exist in data create add all info
$data[$dt_exsis['ID_USER']] = array(
'COA_CODE' => $dt_exsis['COA_CODE'],
'AMOUNT' => $dt_exsis['amount'],
'MODUL' => $dt_exsis['modul'],
'USER_ID' => $dt_exsis['ID_USER']
);
}
}
This will save multiple calls to DB and at the end you can pass $data and do multiple insert.
i am very new to code igniter /php .
Before i was using randomly generated invoice number like
$invoice_no = rand(9999,9999999999);
But now i wanted to increment invoice number and add current year as a prefix to it . But somewhere i am doing wrong as this code failed execute . Can some one point me in the right direction .
My model is ...
function insertInvoice($data)
{
$this->db->trans_begin();
$invoice = array();
if(!empty($data['client_id']))
{
$invoice['invoice_client_id'] = $data['client_id'];
}else{
$client_data = array(
'client_name' => $data['customername'],
'client_address1' => $data['address1']
);
$this->db->insert('client_details', $client_data);
$insert_id = $this->db->insert_id();
$invoice['invoice_client_id'] = $insert_id;
}
$query = $this->db->query("SELECT * FROM invoice ORDER BY invoice_id DESC LIMIT 1");
$result = $query->result_array(0);
$result ++;
$curYear = date('Y');
$invoice_no = $curYear . '-' .$result;
$invoice['invoice_no'] = $invoice_no;
$invoice['invoice_subtotal'] = $data['subTotal'];
$invoice['invoice_tax'] = $data['tax'];
$invoice['invoice_tax_amount'] = $data['taxAmount'];
$invoice['invoice_total'] = $data['totalAftertax'];
$invoice['invoice_total_extra'] = $data['totalextra'];
$invoice['invoice_rent'] = $data['rent'];
$invoice['invoice_paid'] = $data['amountPaid'];
$invoice['invoice_due'] = $data['amountDue'];
$invoice['invoice_desc'] = $data['notes'];
$invoice['invoice_items_count'] = $data['item_count'];
$invoice['invoice_extra_count'] = $data['extra_count'];
$invoice['invoice_miscellaneous'] = $data['miscellaneous'];
$this->db->insert('invoice', $invoice);
$i=1;
do {
$items = array(
'invoice_no' => $invoice_no,
'item_name' => $data['invoice']['product_name'][$i],
'item_price' => $data['invoice']['product_price'][$i],
'item_qty' => $data['invoice']['product_qty'][$i],
'item_total' => $data['invoice']['total'][$i],
'item_noof_crate_wait' => $data['invoice']['noof_crate_wait'][$i],
'item_crate_wait' => $data['invoice']['crate_wait'][$i],
'item_choot' => $data['invoice']['choot'][$i],
'item_net_quantity' => $data['invoice']['net_qty'][$i]
);
$this->db->insert('invoice_items',$items);
$i++;
} while($i<$data['item_count']);
$j=1;
do {
$extraitems = array(
'invoice_no' => $invoice_no,
'extra_item_name' => $data['extra']['name'][$j],
'extra_item_qunatity' => $data['extra']['qty'][$j],
'extra_item_price' => $data['extra']['price'][$j],
'extra_item_total' => $data['extra']['total'][$j]
);
$this->db->insert('extra_items',$extraitems);
$j++;
} while($j<$data['extra_count']);
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
return FALSE;
}
else
{
$this->db->trans_commit();
return TRUE;
}
}
invoice_id is primary key in DB .
You're attempting to increment the result array but what you really need is to acquire and increment a field value.
//you only need one field so ask only for that
$query = $this->db->query("SELECT invoice_id FROM invoice ORDER BY invoice_id DESC LIMIT 1");
//you really should check to make sure $query is set
// before trying to get a value from it.
//You can add that yourself
//Asked for only one row, so only retrieve one row -> and its contents
$result = $query->row()->invoice_id;
$result ++;
...
I'm guessing you're getting an "Object conversion to String error" on line $invoice_no = $curYear . '-' .$result;
Since $result contains an object and you're using it as a string. Print the $result variable to check how to use the data assigned to it.
I have a function which gives me TreeList if I give him $treeData = array(id=1,Name=Abc, ParentId=null). Normally I have table structure like this so there is no problem to provide such array. Problem starts when I have no such structure in table but my client want TreeList for such structure where parent child hierarchy is not directly exists.
What Table Structure I have
Types
Subjects
Topics
Lessons
LessonTypes
In LessonTypes I have TypeId, SubjectId, TopicId, LessonId
I tried to make an array for my function but it is not quite good please see my code:
private function makeTreeDataArray(){
$treeDataArr = array();
$resourceTestTypesArr = array();
$topicArr = array();
$lessonArr = array();
$testTypeIdPrefix = 'TestType#';
$subjectIdPrefix = 'Subject#';
$topicIdPrefix = 'Topic#';
// $model = new ResourceTestType();
//Get All TestTypes into treeDataArr
$model = new Option();
$TestTypes = $model->where('Type','TestType')->get();
foreach ($TestTypes as $k => $TT) {
$testTypeId = $testTypeIdPrefix . $TT->Id;
$treeDataArr[] = array('Id' => $testTypeId, 'Name'=>$TT->Option, 'ParentId' => null);
$resourceTestTypesArr[] = $TT->resourceTestTypes()->get();
}
// return ($resourceTestTypes);
//****Get All Subjects Of TestType
foreach ($resourceTestTypesArr as $i =>$RTTs) {
foreach ($RTTs as $j => $RTT) {
$subjectId = $subjectIdPrefix . $RTT->SubjectId;
$resourceId =$RTT->ResourceId;
$subjectName = $RTT->subject()->first()->Name;
$testTypeIdAsParentId = $testTypeIdPrefix.$RTT->TestTypeId;
$treeDataArr[] = array('Id' => $subjectId, 'Name'=>$subjectName, 'ParentId' => $testTypeIdAsParentId);
//*** Create dataset for Topics
$topicId = $topicIdPrefix.$RTT->TopicId;
$topicIdWithoutPrefix = $RTT->TopicId;
$topicName = Option::getOptionById('Topics',$topicIdWithoutPrefix)->Display;
$topicArr[] = array('topicId' => $topicId, 'topicName'=>$topicName, 'SubjectId' => $subjectId, 'LessonId' => $resourceId);
}
}
// return ($topicArr);
//Get All Topics Of Subject
foreach ($topicArr as $i =>$T) {
$topicId = $T['topicId'];
$lessonId = $T['LessonId'];
$treeDataArr[] = array('Id' => $topicId, 'Name'=> $T['topicName'], 'ParentId' => $T['SubjectId']);
$lessonName = Lesson::find($lessonId)->Name;
$lessonArr[] = array('lessonId' => $lessonId, 'lessonName'=>$lessonName, 'topicId' => $topicId);
}
// return ($lessonArr);
//Get All Lessons Of Topics
foreach ($lessonArr as $i =>$L) {
$treeDataArr[] = array('Id' => $L['lessonId'], 'Name'=> $L['lessonName'], 'ParentId' => 'Topic#'.$L['topicId']);
}
$result = array_unique($treeDataArr,SORT_REGULAR);
// $result = array_unique($treeDataArr);
return $result;
}
And Result of the function is:
-> A-Type
-> A-Subject Of A-Type
-> A-Topic Of A-Subject
-> A-Lesson Of A-Topic
-> B-Topic Of A-Subject
-> A-Lesson Of B-Topic
-> B-Type
-> A-Subject Of A-Type
Notice: A-Subject Appear again here which is not correct it should be appear only inside the A-Type
It happens all others also. Please help me what's wrong with my code. Thanks in advance
This is my sample code:
switch($topic_type) {
case 1: //post
$model = 'Userposts';
$field_name = 'user_post_id';
$select_name = 'post_title';
break;
}
$model = ClassRegistry::init($model);
$model->alias = 'TP';
$model->id = $topic_id;
$result = $model->find('first',
array(
'conditions'=>array($field_name=>$topic_id),
'fields'=>array($select_name.' as topic',$field_name.' as id'),
));
if(!empty($result)){
$this->updata[$model_name][$select_name] = $modified_topic;
$this->updata[$model_name][$field_name] = $topic_id;
if($model->save($this->updata)){
$respArr['token'] = $token;
$respArr['status'] = 1;
$respArr['msg'] = 'Success';
echo json_encode(array('token' => $token, 'status' => 1, 'msg' => 'Success'));exit;
}
}
The $model->find is working and fetching result where as $model->save after find is not working.
field_name is the primary key and select_name is the save that i want to update after modifying title.