Error updating data of 1 column by id in Codeigniter 3 database - codeigniter

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

Related

Validation can not updating value in database

I am uses validation for gst and adhar but when its error free i am updating value but value can not updating. I am giving updating code in else part. what is mistake done by me? need a solution. In if part i am checking validation and in else part if error is not coming, i am updating value from table but i can not work.
public function profile_update(Request $req,$id)
{
$mytime = Carbon::now();
$fullname = $req->input('fullname');
$email = $req->input('email');
$mobile = $req->input('mobile');
$gender = $req->input('gender');
$gstnumber = $req->input('gst_number');
$adharnumber = $req->input('aadhar_number');
$password = $req->input('password');
$cpassword = $req->input('c_password');
$updated_at = $mytime->toDateTimeString();
$created_at = $mytime->toDateTimeString();
$validator = Validator::make($req->all(), [
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
]);
if($validator->fails())
{
//dd("hello");
$messages = $validator->messages();
//return Redirect::to('/customer')->with('message', 'Register Failed');
return redirect('/profile')
->withErrors($validator)
->withInput();
}
else
{
if ($req->hasFile('update_image'))
{
$image = $req->file('update_image');
$filename = $image->getClientOriginalName();
$destinationPath = public_path('/images/users_profile/');
$image->move($destinationPath, $filename);
DB::update(
'update users set name = ?,email = ?,mobile = ?,image = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $filename, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
else
{
DB::update(
'update users set name = ?,email = ?,mobile = ?,gender = ?,gst_number=?,aadhar_number=?,password = ?,cpassword = ? where id = ?',
[$fullname, $email, $mobile, $gender, $gstnumber, $adharnumber, $password, $cpassword, $id]
);
}
return redirect('/profile');
}
}
you dont need the if else statement
$req->validate([
'email' => 'email|unique:users,email',
'aadhar_number' => 'unique:users,aadhar_number' ,
'gst_number' => 'regex:^[0-9]{2}[A-Z]{5}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}Z[0-9A-Z]{1}$^|unique:users,gst_number'
// continue your update code here
]);
Simply do this and it will do the needfull for you
if your conditions are not met by the values it will return to the previous view and if the conditions are met, it will continue to run the codes.
for updating the data
$data = user::find(id);
$data->name = $name;
$data->email = $email;
.
.
.
.
//update all the fields
$data->save();

insert batch codelgniter Unknown column 'Array' in 'field list'

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

Filter admin grid with custom render values Magento

i have created a custom grid in which one of the columns i have render
my custom date.On the basis of data i am returning
yes or no
like below
public function render(Varien_Object $row)
{
$currentruleid = $this->getRequest()->getParam('id');
$value = (int)$row->getData($this->getColumn()->getIndex());
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "SELECT exclusive_coupon_id FROM mutually_exclusive
WHERE rule_id ='$currentruleid' AND exclusive_coupon_id ='$value' ";
$result = $read->query($query);
$affected_rows = $result->rowCount();
if($affected_rows > 0){
return 'Yes';
}
else{
return 'No';
}
}
and in grid my column code is
$this->addColumn('', array(
'header' => Mage::helper('salesrule')->__('Exclusive'),
'index' => 'coupon_id',
'width' => '100',
'type' => 'options',
'options' => array(
Mage::helper('adminhtml')->__('No'),
Mage::helper('adminhtml')->__('Yes')
),
'renderer' => 'adminhtml/promo_quote_edit_tab_exclusivecoupons_grid_column_renderer_used',
));
my renderer is returning accurate data
and its showing in columns
i need to filter also with yes or no. But filtering is not working.
Can you please suggest me how can i do this.
thanks
i have check that but my renderer is not any direct field , its a custom data like below is my renderer function
public function render(Varien_Object $row)
{
$currentruleid = $this->getRequest()->getParam('id');
$value = (int)$row->getData($this->getColumn()->getIndex());
$read = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton("core/resource")->getConnection("core_write");
$query = "SELECT exclusive_coupon_id FROM mutually_exclusive
WHERE rule_id ='$currentruleid' AND exclusive_coupon_id ='$value' ";
$result = $read->query($query);
$affected_rows = $result->rowCount();
if($affected_rows > 0){
return 'Yes';
}
else{
return 'No';
}
}

Integrity constraint violation for key 'UNQ_CATALOG_PRODUCT_SUPER_ATTRIBUTE_PRODUCT_ID_ATTRIBUTE_ID'

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.

CodeIgniter Captcha is not working

I am at my wits end and don't know why my code is not working . Everything seems good to me .. I have implemented a captcha in my user review function and added a verification method using callback_ .
The captcha is showing in the view and i have dumped the session data and the input field data and they are both working.
The form validation is also working in case of captcha input field but seems like the callback_check_captcha parameter is not working but the function seems fine to me .
Here is my controller
function user_review($id = null , $start = 0){
$check_id = $this->mdl_phone->get_phone_feature($id);
if ($check_id == null ) {
$data['phone_model'] = $this->get_phone_models();
$data['feature'] = null;
$data['title'] = 'Nothing Found';
$data['main_content']= 'phone/error';
echo Modules::run('templates/main',$data);
} else{
$data['phone_model'] = $this->get_phone_models();
$data['success'] = null;
$data['errors'] = null;
if($this->input->server("REQUEST_METHOD") === 'POST' ){
$this->load->library('form_validation');
$this->form_validation->set_rules('text','Review','required|xss_clean');
$this->form_validation->set_rules('captcha', 'Captcha','trim|required|callback_check_captcha');
if($this->form_validation->run() == FALSE){
$data['errors'] = validation_errors();
}else{
$user = $this->ion_auth->user()->row();
$user_id = $user->id;
$data = array(
'phone_id' => $id,
'user_id' => $user_id,
'text' => strip_tags($this->input->post('text')),
);
$this->db->insert('user_review' ,$data);
$data['phone_model'] = $this->get_phone_models();
$data['success'] = 'Your Review has been successfully posted ';
$data['errors']= null;
}
}
// Initilize all Data at once by $id
$data['feature'] = $this->mdl_phone->get_phone_feature($id);
//$data['rating'] = $this->mdl_phone->get_user_rating($id);
$data['user_review'] = $this->mdl_phone->get_user_review($id , 5 , $start);
$this->load->library('pagination');
$config['base_url'] = base_url().'phone/user_review/'.$id;
$config['total_rows'] = $this->mdl_phone->get_user_review_count($id);
$config['per_page'] = 5;
$config['uri_segment'] = 4;
$config['anchor_class'] = 'class="page" ';
$this->pagination->initialize($config);
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url().'captcha/',
'img_width' => 150,
'img_height' => 30,
);
$cap = create_captcha($vals);
$this->session->set_userdata('captcha',$cap['word']);
$data['captcha'] = $cap['image'];
$data['title'] = $this->mdl_phone->get_phone_title($id)." User Review , Rating and Popularity";
$data['main_content'] = 'phone/user_review';
echo Modules::run('templates/main',$data);
}
}
function check_captcha($cap)
{
if($this->session->userdata('captcha') == $cap )
{
return true;
}
else{
$this->form_validation->set_message('check_captcha', 'Security number does not match.');
return false;
}
}
The bellow CAPTHA working properly refer this code
$this->load->helper('captcha');
$vals = array(
'img_path' => './captcha/',
'img_url' => base_url() . '/captcha/'
);
$cap = create_captcha($vals);
$data = array(
'captcha_time' => $cap['time'],
'ip_address' => $this->input->ip_address(),
'word' => $cap['word']
);
$this->session->set_userdata($data);
$data['cap_img'] = $cap['image'];
I think your image url problem or you are not giving a file permission to the captha folder .

Resources