i have a problem where i want to update a looping form in codeigniter 3. in column nik_pindah where have a id_surat is same
---MY CONTROLLER WITH FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
$this->load->library('form_validation');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null){
foreach ($a as $row => $val){
$this->form_validation->set_rules("nik_pindah[$i]","nik_pindah", "integer|callback_nik_pindah_available");
}
}
$this->form_validation->set_message('required', 'Mohon isi %s terlebih dahulu');
$this->form_validation->set_message('integer', 'Isi %s hanya menggunakan angka');
if ($this->form_validation->run() == FALSE){
$this->edit_nik_pindah_kelurahan($id_surat_pindah);
} else {
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row) {
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY CONTROLLER WITHOUT FORM VALIDATION---
public function update_nik_pindah_kelurahan($id_surat_pindah){
if ($this->form_validation->run() == FALSE){
$id_surat_pindah = $this->input->post('id_surat_pindah');
$id_surat = $this->input->post('id_surat');
$i = 0; // untuk loopingnya
$a = $this->input->post('nik_pindah');
if ($a[0] !== null) {
$data = array(
'id_surat' => $id_surat,
'id_surat_pindah' => $id_surat_pindah
);
foreach ($a as $row){
$dataaa = [
'id_surat' => $id_surat_pindah,
'nik_pindah' =>$row,
];
$wheree = array(
'id_surat' => $id_surat_pindah
);
$this->db->where('id_surat', $id_surat_pindah);
$update = $this->db->update('nik_pindah', $dataaa);
if ($update) {
$i++;
}
}
$where = array(
'id_surat_pindah' => $id_surat_pindah
);
$this->m_pindah_kelurahan->update_data($where, $data, 'surat_pindah');
}
redirect('admin_pindah_kelurahan/index');
}
}
---MY VIEWS---
<?php
foreach ($nik_pindah_kelurahan as $np) :
if (empty($np->nik_pindah)) { ?>
<input type="text" name="nik_pindah" class="form-control" value="belum tersedia"><br>
<?php } else {?>
<input type="text" name="nik_pindah[]" class="form-control" value="<?php echo $np->nik_pindah ?>"><br>
<?php } endforeach; ?>
If with or without form validation will updating data but all column where id_surat is same (not particular value)
like this:
enter image description here then enter image description here
Everytime the foreach makes a loop, $this->db->where() has the same condition because $id_surat_pindah has always the same value, so you're updating the same rows once and once again. Also (if I understand it correctly), keep in mind that if $id_surat_pindah is not a unique key, everytime you make an UPDATE all the rows with its value will be affected.
Otherwise, I would recommend you to check your code using update_batch() instead the loop: https://www.codeigniter.com/userguide3/database/query_builder.html?highlight=update_batch
Related
I have a simple question that needs to get an element when selecting that reference ID by an input form. I used the following code to do that.
$id2=$locationProducts[0]->inventory_update_stock_details_id;
But this code outs only the first element always. AS an exmple inventory_update_stock_details_id=36, inventory_update_stock_details_id=36, inventory_update_stock_details_id=36 and so on.
But I needs to select as inventory_update_stock_details_id=35, inventory_update_stock_details_id=345, inventory_update_stock_details_id=2 like that.
inventory_update_stock_details_id included ids as 1,2,3,4,5,......1000
The model as follows :
function getInventoryLocationProducts()
{
$this->db->select("*");
$this->db->from('store_inventory_update_stock_details');
$this->db->join('store_inventory_item', 'store_inventory_item.inventory_item_id=store_inventory_update_stock_details.inventory','left');
$this->db->join('store_inventory_location_update', 'store_inventory_location_update.inventory_update_stock_id=store_inventory_update_stock_details.inventory_update_stock_id','left');
$this->db->join('store_inventory_update_stock', 'store_inventory_update_stock.inventory_update_stock_id=store_inventory_location_update.inventory_update_stock_id','left');
$this->db->where('store_inventory_item.status=1');
$this->db->where('store_inventory_update_stock_details.serial_no NOT IN (select serial_no from store_inventory_location_update)');
$q = $this->db->get_where();
if ($q->num_rows() > 0) {
return $q->result();
}
return FALSE;
}
Controller
public function addInventoryLocation()
{
$this->checkPermissions('add', 'inventoryLocation');
$bc = array(array('link' => '#', 'page' => 'Inventory Locations'));
$meta = array('page_title' => 'Inventory Locations', 'bc' => $bc);
$this->data['branch'] = $this->Item_model->getBranch();
$this->data['office'] = $this->Item_model->getOffice();
$locationProducts = $this->Item_model->getInventoryLocationProducts();
$this->data['locationProducts'] = $locationProducts;
$this->data['auto_loc_no'] = $this->Item_model->generate_inv_loc_ref();
$count = $this->input->post('i');
$str = $this->input->post('auto_loc_no');
$auto_loc = preg_replace("/[^0-9]{1,4}/", '', $str);
$this->form_validation->set_rules('branch', 'Branch', 'required');
if ($this->form_validation->run() == true) {
$stock = array(
'office_id' => $this->input->post('office'),
'branch' => $this->input->post('branch'),
'l_date' => $this->input->post('l_date'),
'is_order_no' => $this->input->post('is_order_no'),
'loc_no' => $this->input->post('auto_loc_no'),
'auto_loc_no' => $auto_loc,
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'locate',
'status' => 1
);
$id = $this->Item_model->addInventoryLocation($stock);
}
$id2=$locationProducts[0]->inventory_update_stock_details_id;
dd($id2);
if ($this->form_validation->run() == true && $id2 != 0) {
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[$x]['inventory_update_stock_id'] = $id2;
$details[$x]['inventory'] = $this->input->post('inventory' . $x);
$details[$x]['serial_no'] = $this->input->post('serial_no' . $x);
$details[$x]['item_code'] = $this->input->post('item_code' . $x);
$details[$x]['officer'] = $this->input->post('officer' . $x);
$details[$x]['qty'] = 1;
$details[$x]['status'] = 1;
$details[$x]['branch'] = $this->input->post('branch');
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/addInventoryLocation', $meta, $this->data);
}
}
View
<td style="width: 30%">
<input type="hidden" name="i" id="i" value="0">
<select name="inventory0" id="inventory0" class="form-control select2 inventory-select" required>
<option value=""></option>
<?php
if (!empty($locationProducts)) {
foreach ($locationProducts as $row) {
echo "<option value='".$row->inventory_update_stock_details_id."'> $row->inventory_update_stock_details_id - $row->inventory_item_name</option>";
?>
<?php
}
}
?>
</select>
</td>
What can modify my code line to do that. Can anyone help me ?
I'm not entirely sure what the intended logic is, but I think what you want is to add the InventoryLocationDetails to all InventoryLocationProducts.
If that is correct, you could perhaps do something like this:
if ($this->form_validation->run() == true) {
$details = [];
foreach ($locationProducts as $locationProduct) {
$id2 = $locationProduct->inventory_update_stock_details_id;
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[] = [
'inventory_update_stock_id' => $id2,
'inventory' => $this->input->post('inventory' . $x),
'serial_no' => $this->input->post('serial_no' . $x),
'item_code' => $this->input->post('item_code' . $x),
'officer' => $this->input->post('officer' . $x);
'qty' => 1,
'status' => 1,
'branch' => $this->input->post('branch'),
];
}
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
}
This assumes that $locationProducts contains only those products that actually need to be updated. If you need to only update some of them, you can add the logic to determine which product to update inside the foreach loop.
This method i am using for storing currentTime in database using ajax call and its working
public function saveTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 404]);
}
$video = \App\Lession::where('id',$lession_id)->first();
$lesson_id = $request->lession_id;
$progress = $request->time;
//save them somewhere
$watch_history = $user->watch_history;
$watch_history_array = array();
if ($watch_history == '') {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
} else {
$founder = false;
$watch_history_array = json_decode($watch_history, true);
for ($i = 0; $i < count($watch_history_array); $i++) {
$watch_history_for_each_lesson = $watch_history_array[$i];
if ($watch_history_for_each_lesson['lession_id'] == $lesson_id) {
$watch_history_for_each_lesson['progress'] = $progress;
$watch_history_array[$i]['progress'] = $progress;
$founder = true;
}
}
if (!$founder) {
array_push($watch_history_array, array('lession_id' => $lesson_id, 'progress' => $progress));
}
}
$data['watch_history'] = json_encode($watch_history_array);
$check = User::where('id',$user->id)->update(['watch_history' => $watch_history_array]);
return response()->json(['message' => 'Time saved', 200]);//send http response as json back to the ajax call
}
But when I use this another method to get the time back for playback it's getting the array inside an array
public function getTime(Request $request, $lession_id){
$user = Auth::user();
if($user === null){
return response()->json(['message' => 'User not authenticated', 403]);
}
$user_video = User::where('id',$user->id)->first();
$array = $user_video->watch_history;
foreach ($array as $key => $value) {
echo $check;
}
}
My current Output in a database is as follows
[{"lession_id":"157","progress":"71.449464"},{"lession_id":"156","progress":"92.113123"}]
So help me to get the values out of that for each lession id
I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
I am using Laravel 5.2 Backpack in my new project where I have a select_from_array field in my form, depending upon the selected value I want data to be displayed in another select_from_array field. Don't know how to do that. Please help me with this. This is my code
Controller.php
public function __construct()
{
if (Request::segment(3) == 'create') {
$parentField1 = [
'name' => 'cat_id',
'label' => 'Category',
'type' => 'select_from_array',
'options' => $this->categories(),
'allows_null' => false,
];
$parentField = [
'name' => 'subCat_id',
'label' => 'SubCategory',
'type' => 'select_from_array',
'options' => $this->subcategories(),
'allows_null' => false,
];
array_unshift($this->crud['fields'], $parentField1,$parentField);
}
public function categories()
{
$cat = Request::get('cat_id');
$currentId = 0;
if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
$currentId = Request::segment(3);
}
$entries = Category::where('translation_lang', config('app.locale'))->where('parent_id',0)->orderBy('lft')->get();
if (is_null($entries)) {
return [];
}
$tab = [];
$tab[0] = 'Root';
foreach ($entries as $entry) {
if ($entry->id != $currentId) {
$tab[$entry->translation_of] = '- ' . $entry->name;
}
}
return $tab;
}
public function subcategories()
{
$currentId = 0;
if (Request::segment(4) == 'edit' and is_numeric(Request::segment(3))) {
$currentId = Request::segment(3);
}
$entries = Category::where('translation_lang', config('app.locale'))->where('parent_id','!=' ,0)->orderBy('lft')->get();
if (is_null($entries)) {
return [];
}
$tab = [];
$tab[0] = 'Root';
foreach ($entries as $entry) {
if ($entry->id != $currentId) {
$tab[$entry->translation_of] = '- ' . $entry->name;
}
}
return $tab;
}
I want the id of selected option in the subcategories() where I can use the id to get the data.
I think the best way for you is to create a custom field type for this particular purpose, that includes both selects. Follow this procedure. Start from the select2.blade.php file and add the javascript you need to achieve your goal (on change event on first select2, change the options in the next select2).
I'm just practicing using session in Codeigniter and i've got a Problem here's my controller
public function ajax_Addfees()
{
if($this->input->is_ajax_request())
{
$input = $this->input->post();
if($this->session->userdata('html')){
$html = $this->session->userdata('html');
}
$id = explode($input['fno']);
$html[$id] = ['amount' => $input['amount'], 'oldamount' => $input['deduction']];
$this->session->set_userdata('html', $html);
}
}
public function savetuition()
{
$this->Tuition_model->savefees();
redirect('tuitionsetup_con');
}
This is my model
public function savefees()
{
$fees = $this->session->userdata('html');
$feeslist = [];
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
array_push($feeslist, [
'amount' => $value['amount'],
'oldamount' => $value['oldamount'],
'f_no' => $key,
'sy_no' => $this->session->userdata('sy'),
'level_no' => $this->session->userdata('lvl'),
'id' => $this->session->userdata('id')
]);
$this->db->insert_batch('tuition', $feeslist);
} }
}
Well what I'm trying to do is to save data from session->set_userdata('html') to my database using codeigniter.
There's no error but it doesn't save data to database
You need to modify your model as:
public function savefees() {
$fees = $this->session->userdata('html');
$feeslist = array();
if( !empty($fees) ) {
foreach ($fees as $key =>$value) {
$feeslist[$key]["amount"] = $value['amount'];
$feeslist[$key]["oldamount"] = $value['oldamount'];
$feeslist[$key]["f_no"] = $key;
$feeslist[$key]["sy_no"] = $this->session->userdata('sy');
$feeslist[$key]["level_no"] = $this->session->userdata('lvl') ;
$feeslist[$key]["id"] = $this->session->userdata('id') ;
}
}
$this->db->insert_batch('tuition', $feeslist);
}