I am beginner in CI. I am getting an error in insert_batch function in CodeIgniter. When I insert array into insert_batch I get this error
Unknown column 'Array' in 'field list'
and
Array to string conversion
I've done many solutions but still get this error,
Can anyone give me an idea?
thanks in advance
in my views
<input type="text" name="companionship[]"> and so forth.
controller
public function addstatistics()
{
$i =0;
foreach($_POST['companionship_id'] as $companionship_id):
$value1[$i++] = array(
'companionship_id'=> $companionship_id
);
endforeach;
foreach($_POST['zone_id'] as $zone_id):
$value2[$i++] = array(
'zone_id'=> $zone_id
);
endforeach;
foreach($_POST['district_id'] as $district_id):
$value3[$i++] = array(
'district_id'=> $district_id
);
endforeach;
foreach($_POST['area_id'] as $area_id):
$value4[$i++] = array(
'area_id'=> $area_id
);
endforeach;
foreach($_POST['baptism'] as $baptism):
$value5[$i++] = array(
'baptism'=> $baptism
);
endforeach;
foreach($_POST['confirm'] as $confirm):
$value6[$i++] = array(
'confirm'=> $confirm
);
endforeach;
foreach($_POST['ibd'] as $ibd):
$value7[$i++] = array(
'ibd'=> $ibd
);
endforeach;
foreach($_POST['iasm'] as $iasm):
$value8[$i++] = array(
'iasm'=>$iasm
);
endforeach;
foreach($_POST['ni'] as $ni):
$value9[$i++] = array(
'ni'=>$ni
);
endforeach;
foreach($_POST['ph'] as $ph):
$value10[$i++] = array(
'ph'=>$ph
);
endforeach;
foreach($_POST['wh'] as $wh):
$value11[$i++] = array(
'wh'=>$wh
);
endforeach;
$this->my_model->addstatistics($value1,$value2,$value3,$value4, $value5,$value6,$value7,$value8,$value9,$value10,$value11);
}
MODEL function
addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $value1,
'zone_id'=> $value2,
'district_id'=> $value3,
'area_id'=> $value4,
'baptism'=> $value5,
'confirm'=> $value6,
'ibd'=> $value7,
'iasm'=> $value8,
'ni'=> $value9,
'ph'=> $value10,
'wh'=> $value11,
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
Can anybody give me idea on how can i solve this problem?
Try this.
public function addstatistics($value1,$value2,$value3,$value4,$value5, $value6,$value7,$value8,$value9,$value10,$value11)
{
$data = array(
'companionship_id' => $value1,
'zone_id' => $value2,
'district_id' => $value3,
'area_id' => $value4,
'baptism' => $value5,
'confirm' => $value6,
'ibd' => $value7,
'iasm' => $value8,
'ni' => $value9,
'ph' => $value10,
'wh' => $value11
);
$row = array();
$columns = array();
for($x=0; $x<count($data); $x++)
{
$row = array(
'companionship_id'=> $data['companionship_id'][$x]['companionship_id'],
'zone_id'=> $data['zone_id'][$x]['zone_id'],
'district_id'=> $data['district_id'][$x]['district_id'],
'area_id'=> $data['area_id'][$x]['area_id'],
'baptism'=> $data['baptism'][$x]['baptism'],
'confirm'=> $data['confirm'][$x]['confirm'],
'ibd'=> $data['ibd'][$x]['ibd'],
'iasm'=> $data['iasm'][$x]['iasm'],
'ni'=> $data['ni'][$x]['ni'],
'ph'=> $data['ph'][$x]['ph'],
'wh'=> $data['wh'][$x]['wh'],
'year'=> date('Y'),
'month'=> date('M'),
'week' => weekdate(),
'created_by'=> $this->session->userdata('login_id')
);
array_push($columns, $row);
$rows = array();
}
//printA($columns);
$query= $this->db->insert_batch('monthly_statistics', $columns);
}
after a few hours of pondering, I already fix the errors
and now it working fine
here is the code
public function mymethod()
{
$companionship_id = $this->input->post('companionship_id[]');
$zone_id = $this->input->post('zone_id[]');
$district_id = $this->input->post('district_id[]');
$area_id = $this->input->post('area_id[]');
$baptism = $this->input->post('baptism[]');
$confirm = $this->input->post('confirm[]');
$ibd = $this->input->post('ibd[]');
$iasm = $this->input->post('iasm[]');
$ni = $this->input->post('ni[]');
$ph = $this->input->post('ph[]');
$wh = $this->input->post('wh[]');
$value = array();
for($i=0; $i<count($companionship_id); $i++)
{
$value[$i] = array(
'companionship_id' => $companionship_id[$i],
'zone_id' => $zone_id[$i],
'district_id' => $district_id[$i],
'area_id' => $area_id[$i],
'baptism' => $baptism[$i],
'confirm' => $confirm[$i],
'ibd' => $ibd[$i],
'iasm' => $iasm[$i],
'ni' => $ni[$i],
'ph' => $ph[$i],
'wh' => $wh[$i]
);
}
$this->db->insert_batch('monthly_statistics',$value);
$this->session->set_flashdata("success",alert("alert-success","Successfully Inserted"));
redirect(base_url('to_url'));
exit();
}
Related
I am posting the hosting order and I want to increase the "number of sales" column in my "hostings" table, but the data of all packages in my hostings table is increasing.
Here is my relevant code, I can say that there is no method I haven't tried.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
//FULL CODE
public function buy_hosting_post()
{
if ($this->input->post('package_id') && $this->session->userdata('id')) {
$hosting = $this->db->from('hostings')->where('id', $this->input->post('package_id'))->get()->row_array();
if ($hosting) {
$data = array(
'user_id' => $this->session->userdata('id'),
'domain' => $this->input->post('domain'),
'price' => $this->input->post('price'),
// 'end_date' => date('Y-m-d h:i:s',$end_date),
'package_id' => $hosting['id'],
'package_title' => $hosting['name'],
'payment_status' => 0,
);
$this->db->insert('hosting_orders', $data);
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->update('hostings', $data);
$hosting_order_successful = array(
'hosting_order_successful' => 'success',
);
$this->session->set_userdata('hosting_order_successful', $hosting_order_successful);
redirect(("hosting-siparisi-olusturuldu"));
} else {
redirect(base_url());
}
} else {
redirect(base_url());
}
}
I solved the problem in the following way, but it makes the system heavy.
$hostingdata = $this->db->query("select number_of_sales from hostings where id=" . $this->input->post('package_id'))->row();
$quantity = 1;
$new_number_of_sales = $hostingdata->number_of_sales + $quantity;
$data = array(
'number_of_sales' => $new_number_of_sales
);
$this->db->where('id', $this->input->post('package_id')); // added here.
$this->db->update('hostings', $data);
Suppose I have items in database which is stored from an Excel file. All the items should be below the header of the months. I have also stored months from the file in the database. So, I want those months to be the header of those items and it's related records. In simple words, I want the header to be dynamic. This is what I have done.
I have tried many code scripts but nothing works. Like Laravel, Excel etc. Can anyone suggest me a good approach?
public function test(){
$data = Item::where('category_id',7)->get()->toArray();
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $value) {
// dd($value);
$itemsArray[] = array(
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:D1';
// $spreadsheet->getActiveSheet()->getStyle('A1:D4')
// ->getAlignment()->setWrapText(true);
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '15' );
$sheet->setBorder($cellRange, 'thick' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I need help for getting the actual result.
Akhtar i suggest use to kindly install the Carbon package
https://carbon.nesbot.com/docs/
Try by updating the below code.
$data = Item::where('category_id',7)->get(); // removed toArray()
$data2 = month::all();
$itemsArray[] = ['Category Id','Item Name','Created At','Updated At'];
foreach ($data as $key=>$value) {
$itemsArray[] = array(
'month' => Carbon::now()->addMonth($key)->format('m-Y');
'Category Id' => $value['category_id'],
'Item Name' => $value['name'],
'Created At' => $value['created_at'],
'Updated At' => $value['updated_at'],
);
}
This is the actual code which I have used for excel file. I have solved my problem. Thanks and yeah I am posting this code, if anyone can get help from it.
public function export(){
$data = Category::all();
foreach ($data as $value) {
$value['items'] = Item::where('category_id',$value['id'])->get();
foreach ($value['items'] as $vl) {
$vl['record'] = Record::where('item_id',$vl['id'])->get();
}
}
$data2 = month::pluck('id','month');
foreach ($data2 as $key => $value) {
$m[] = $key;
}
array_unshift($m, 'Categories'); //Insert new element at the start of array
array_push($m, 'Total');
$itemsArray[] = $m;
foreach ($data as $value) {
$itemsArray[] = array(
$itemsArray[0][0] => $value['name'],
// $itemsArray[0][13] => 'Total',
);
foreach ($value['items'] as $val) {
$records_array = [];
$i = 0;
foreach ($val['record'] as $val5) {
$recordval = $val5['value'];
$records_array[$i] = $val5['value'];
$i++;
}
$itemsArray[] = array(
$itemsArray[0][0] => $val['name'],
$itemsArray[0][1] => $records_array[0],
$itemsArray[0][2] => $records_array[1],
$itemsArray[0][3] => $records_array[2],
$itemsArray[0][4] => $records_array[3],
$itemsArray[0][5] => $records_array[4],
$itemsArray[0][6] => $records_array[5],
$itemsArray[0][7] => $records_array[6],
$itemsArray[0][8] => $records_array[7],
$itemsArray[0][9] => $records_array[8],
$itemsArray[0][10] => $records_array[9],
$itemsArray[0][11] => $records_array[10],
$itemsArray[0][12] => $records_array[11],
// $itemsArray[0][13] => 'Total',
);
}
}
// Generate and return the spreadsheet
Excel::create('Items', function($excel) use ($itemsArray) {
// Set the spreadsheet title, creator, and description
$excel->setTitle('Items');
// Build the spreadsheet, passing in the items array
$excel->sheet('Items', function($sheet) use ($itemsArray) {
$cellRange = 'A1:M1';
$sheet->getStyle($cellRange)->getFont()->setBold( true );
$sheet->getStyle($cellRange)->getFont()->setSize( '12' );
$sheet->setBorder($cellRange, 'thin' );
$sheet->getStyle($cellRange)->applyFromArray(array(
'fill' => array(
// 'type' => PHPExcel_Style_Fill::FILL_SOLID,
'color' => array('rgb' => 'A5D9FF')
)
));
$sheet->fromArray($itemsArray, null, 'A1', false, false);
});
$excel->setCreator('Laravel')->setCompany('Dev505');
$excel->setDescription('Items file');
})->download('xlsx');
}
I am using Codeigniter 3.x and want to see an update_batch query, but not run it, while I am debugging the code.
This works for an update_batch:
$this->db->update_batch("`" . $this->fullGamesTable . "`", $fullGames, 'gameid');
and updates the database, but I want to view the update and not actually do the update.
Thanks.
Can you do like this
$data = array(
array(
'opt_id' => $hoptid1,
'q_id' => $hid,
'opt_val' => $sin_yes,
'opt_crct' => $sin_yescrt,
'opt_mark' => '1'
),
array(
'opt_id' => $hoptid2,
'q_id' => $hid,
'opt_val' => $sin_no,
'opt_crct' => $sin_nocrt,
'opt_mark' => '1'
)
);
$this->db->update_batch('option', $data, 'opt_id');
Try this
public function update_batch()
{
$data = $this->db->select('id,description')->from('insert_batch')->group_by('url')->get()->result_array();
$batch_update = [];
foreach ($data as $key => $value) {
$value['description'] = 'description';
$batch_update[] = [
'id' =>$value['id'],
'description' => $value['description']
];
}
echo "<pre>"; print_r($batch_update);
$this->db->update_batch('insert_batch',$batch_update,'id');
}
i am using drupal_validate_form on a node listing page .
it is validating it correctly only for 1st item after that it is not checking validation.
here is my code
foreach($result as $r){
$node_form = (object) array(
'uid' => $user->uid,
'type' => 'MY_CONTENT_TYPE',
'language' => LANGUAGE_NONE,
);
$form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
$form['#submit'] = array('#type' => 'submit', '#value' => t('Next'));
$old_fs = #unserialize($r->form_state);
$old_fs['values']['uid'] = $user->uid;
$node = (object) array(
'uid' => $user->uid,
'type' => 'MY_CONTENT_TYPE',
'language' => LANGUAGE_NONE,
);
node_object_prepare($node);
$form_state = array();
$form_state['build_info']['args'] = array($node);
$form_state['values'] = $old_fs['values'];
$form_state['values']['op'] = t('Save');
$form_state['submitted'] = 1;
$form_state['complete form'] = array();
$form_state['triggering_element'] = array('#parents'=>array('next'),'#button_type'=>'submit');
unset($form['#token']);
drupal_validate_form('MY_CONTENT_TYPE_node_form', $form, $form_state);
$errors = form_get_errors();
$noOfError = 'empty';
if (!empty($errors)) {
$noOfError = count($errors);
}
form_clear_error();
}
thank You in advance
Finally i have to reset need_validation in $form .
Because every time form get for validation it will chack $form['#needs_validation'] in _form_validate();
so i added another line after
$form = drupal_get_form('MY_CONTENT_TYPE_node_form',$node_form);
$form['#needs_validation'] = TRUE;
and it will validate every form in that loop
I am creating simple products and then configurable product followed by associating simple products with configurable product. When I run the code for the first time, it works smoothly creating all simple products, configurable product and also an association. But, when I run that code again it says constraint violation. The ID that shows duplicated is the same product ID that was created the last time, when all process were ok.
My code is the following one.
$product_collection = Mage::getModel('catalog/product')
->getCollection()
->addAttributeToSelect('*');
$toinsertId = $product_collection->getLastItem()->getId() + 1;
$configurable_attribute = "art_print_sizes";
$attr_id = 133;
$simpleProducts = array();
$lowestPrice = 999999;
$attributes = Mage::getModel('catalogsearch/advanced')->getAttributes();
$attributeArray = array();
foreach ($attributes as $a) {
if ($a->getAttributeCode() == 'art_print_sizes') {
$count = 0;
foreach ($a->getSource()->getAllOptions(false) as $option) {
$option_id = $this->getOptionId("art_print_sizes", $option['label']);
$sku = 'SK_' . '500' . '_' . strval($count);
$sProduct = Mage::getModel('catalog/product');
$sProduct
->setTypeId(Mage_Catalog_Model_Product_Type::TYPE_SIMPLE)
->setWebsiteIds(array(1))
->setStatus(Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
->setTaxClassId(5)
->setAttributeSetId(9)
->setSku($sku)
// $main_product_data is an array created as part of a wider foreach loop, which this code is inside of
->setName($wholedata['name'] . " - " . $option['label'])
->setShortDescription($wholedata['short_description'])
->setDescription($wholedata['description'])
->setPrice(sprintf("%0.2f", $wholedata['attr_val'][$count]))
->setData($configurable_attribute, $option_id);
$sProduct->save();
array_push(
$simpleProducts,
array(
"id" => $sProduct->getId(),
"price" => $sProduct->getPrice(),
"attr_code" => 'art_print_sizes',
"attr_id" => $attr_id,
"value" => $option_id,
"label" => $option['label']
)
);
$count++;
}
}
}
$cProduct = Mage::getModel('catalog/product');
$productData = array(
'name' => 'Main configurable Tshirt',
'sku' => 'tshirt_sku',
'description' => 'Clear description about your Tshirt that explains its features',
'short_description' => 'One liner',
'weight' => 1,
'status' => '1',
'visibility' => '4',
'attribute_set_id' => 9,
'type_id' => 'configurable',
'price' => 1200,
'tax_class_id' => 0
);
foreach ($productData as $key => $value) {
$cProduct->setData($key, $value);
}
$cProduct->setStockData(
array(
'manage_stock' => 1,
'is_in_stock' => 1,
'qty' => 0,
'use_config_manage_stock' => 0
)
);
$cProductTypeInstance = $cProduct->getTypeInstance();
$attribute_ids = array(133);
$cProductTypeInstance->setUsedProductAttributeIds($attribute_ids);
$attributes_array = $cProductTypeInstance->getConfigurableAttributesAsArray();
foreach ($attributes_array as $key => $attribute_array) {
$attributes_array[$key]['use_default'] = 1;
$attributes_array[$key]['position'] = 0;
if (isset($attribute_array['frontend_label'])) {
$attributes_array[$key]['label'] = $attribute_array['frontend_label'];
} else {
$attributes_array[$key]['label'] = $attribute_array['attribute_code'];
}
}
$cProduct->setConfigurableAttributesData($attributes_array);
$dataArray = array();
foreach ($simpleProducts as $simpleArray) {
$dataArray[$simpleArray['id']] = array();
foreach ($attributes_array as $key => $attrArray) {
array_push(
$dataArray[$simpleArray['id']],
array(
"attribute_id" => $simpleArray['attr_id'][$key],
"label" => $simpleArray['label'][$key],
"is_percent" => 0,
"pricing_value" => $simpleArray['pricing_value'][$key]
)
);
}
}
$cProduct->setConfigurableProductsData($dataArray);
$cProduct->setCanSaveConfigurableAttributes(true);
$cProduct->setCanSaveCustomOptions(true);
$cProduct->save();
The Error is like this
Product ID 126 is already added in database in previous session. And previous session went well adding all necessary products.
Magento will not allow you to update configurable products. So for resolve it just add below code
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
before
$cProduct->setConfigurableAttributesData($attributes_array);
So your final code will be
if($productId){
$resource = Mage::getSingleton('core/resource');
$write = $resource->getConnection('core_write');
$table = $resource->getTableName('catalog/product_super_attribute');
$write->delete($table,"product_id = " . $productId);
}
$cProduct->setConfigurableAttributesData($attributes_array);
Note: Change $productId variable according to your code. You have to pass product id here.