I am using CodeIgniter, I am displaying the fields dynamically. Now I have to insert the data in the database. So I tried below code.
$order = $this->input->post('order[]');
$partner = $this->input->post('parner[]');
$bankname = $this->input->post('newpartner[]');
$status = $this->input->post('filestatus[]');
$user_id = $this->input->post('user_id');
$order_length = sizeof($order);
for ($j = 0; $j < $order_length; $j++) {
if (($status = 1) || ($status = 3)) {
$remark = $this->input->post('remark[]');
} else {
$remark = "";
}
if (($status = 2) || ($status = 4))) {
$reasonDate = $this->input-> post('reasonDate[]');
$remark = $this->input-> post('remark[]');
} else {
$reasonDate = "";
$remark = "";
}
if ($status = 7) {
$reasonAmt = $this->input->post('reasonAmt[]');
$reason = $this->input->post('reason[]');
} else {
$reasonAmt = "";
$reason = "";
}
$data['row'] = array(
'order' => $order[$j],
'bankname' => $bankname[$j],
'status' => $status[$j],
'lead_id' => $user_id,
'remark' => $remark[$j],
'reasonDate' => $reasonDate[$j],
'reasonAmt' => $reasonAmt[$j],
'reason' => $reason[$j]
);
$save = array(
'b_orderno' => $data['row']['order'],
'b_bankname' => $data['row']['bankname'],
'b_filestatus' => $data['row']['status'],
'p_id' => $data['row']['pid'],
'lead_id' => $data['row']['lead_id'],
'b_remark' => $data['row']['remark'],
'b_date' => $data['row']['reasonDate'],
'b_amt' => $data['row']['reasonAmt'],
'b_reason' => $data['row']['reason']
);
$afterxss = $this->security-> xss_clean($save);
if ($afterxss) {
$this - > db - > insert('tbl_bankdata', $afterxss);
$response['error'] = "true";
$response['msg'] = "added successfully";
} else {
$response['error'] = "false";
$response['msg'] = "Sometning wrong! please check the internet connection and try again";
}
}
echo json_encode($response);
I am getting the issue on the status field because depending upon the status value input field will display. Also, I used If the condition in logic for the status field. Each row has a unique status field.
You will find my HTML and script in below link.
https://jsfiddle.net/08phzue3/
This is my UI screenshot. Ignore the value that is only for testing purpose.
1)Onload this will display
2) If user select the status
3) If multiple row
Would you help me out with this?
Actually you are not comparing here:
if (($status = 1) || ($status = 3)) {
You are assigning the values to your $status variable
this should be:
if (($status == 1) || ($status == 3)) {
Side note: same for other conditions as well.
Edit:
As you mentioned you are getting array in $status so using comparison is not a correct logic here, there are multiple solution available,
You can use in_array() like:
if(in_array(1, $status) || in_array(3, $status)){
$remark = $this->input->post('remark[]');
}
else{
$remark = "";
}
Final Solutions (04-07-2019):
After changing the $save and $data arrays, issue has been resolved for OP:
$save['b_orderno'] = $order[$j];
$save['b_bankname'] = $bankname[$j];
$save['b_filestatus'] = $status[$j];
$save['p_id'] = $partner[$j];
$save['lead_id'] = $user_id;
if(!empty($remark[$j])){
$save['b_remark'] = $remark[$j];
}
if(!empty($reasonDate[$j])){
$save['b_date'] = $reasonDate[$j];
}
if(!empty($message[$j])){
$save['b_message'] = $message[$j];
}
if(!empty($reasonAmt[$j])){
$save['b_amt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$save['b_reason'] = $reason[$j];
}
$data['row']['order'] = $order[$j];
$data['row']['bankname'] = $bankname[$j];
$data['row']['status'] = $status[$j];
$data['row']['lead_id'] = $user_id;
$data['row']['remark'] = $remark[$j];
$data['row']['reasonDate'] = $reasonDate[$j];
if(!empty($reasonAmt[$j])){
$data['row']['reasonAmt'] = $reasonAmt[$j];
}
if(!empty($reason[$j])){
$data['row']['reason'] = $reason[$j];
}
Related
I have been creating API for Mobile App. My Task is to check whether email / phone no already exists. If so i should display the error as "Already Exist".
../models/Model_api.php
public function customer_email_check($customer_email){
$customer_email = $this->input->post('customer_email');
$this->db->where('customer_email', $customer_email);
$result = $this->db->get('customers_info');
if($result->num_rows() > 0){
/*
* the email already exists
* */
return false;
}
}
public function customer_phoneno_check($customer_phone_no){
$customer_phone_no = $this->input->post('customer_phone_no');
$this->db->where('customer_phone_no', $customer_phone_no);
$result = $this->db->get('customers_info');
if($result->num_rows() > 0){
/*
* the phone already exists
* */
return false;
}
}
../controllers/Api.php
public function customer_register_api(){
$path = $_FILES['customer_image']['name'];
$path_tmp = $_FILES['customer_image']['tmp_name'];
$final_name = $path;
move_uploaded_file( $path_tmp, './public/images/customers/'.$final_name );
$customer_name = $_POST['customer_name'];
$customer_image = $final_name;
$customer_address = $_POST['customer_address'];
$customer_city = $_POST['customer_city'];
$customer_state = $_POST['customer_state'];
$customer_pincode = $_POST['customer_pincode'];
$customer_phone_no = $_POST['customer_phone_no'];
$customer_email = $_POST['customer_email'];
$customer_password = md5($_POST['customer_password']);
$status = $_POST['status'];
//$existent_phoneno = $this->Model_api->existent_phoneno($this->input->post('customer_phone_no'));
//$existent_email = $this->Model_api->existent_email($this->input->post('customer_email'));
$customer_email_check = $this->Model_api->customer_email_check();
$customer_phoneno_check = $this->Model_api->customer_phoneno_check();
if(!$customer_name || !$customer_image || !$customer_address || !$customer_city || !$customer_state || !$customer_pincode || !$customer_phone_no || !$customer_email || !$customer_password || !$status){
//$this->response("Enter complete Product information to save", 400);
echo json_encode (
array(
"status"=>'false',
"error"=>'All Fields are Mandatory',
));
}elseif ($customer_email_check === 1) {
//elseif (!empty($existent_phoneno) || ($existent_email)) {
echo json_encode (
array(
"status"=>'false',
"error"=>'Email Already Exists',
));
}elseif ($customer_phoneno_check === 1) {
//elseif (!empty($existent_phoneno) || ($existent_email)) {
echo json_encode (
array(
"status"=>'false',
"error"=>'Phone Already Exists',
));
}else{
$result = $this->Model_api->add_customer(array("customer_name"=>$customer_name, "customer_image"=>$customer_image, "customer_address"=>$customer_address, "customer_city"=>$customer_city, "customer_state"=>$customer_state, "customer_pincode"=>$customer_pincode, "customer_phone_no"=>$customer_phone_no, "customer_email"=>$customer_email, "customer_password"=>$customer_password, "status"=>$status));
if($result === 0){
echo json_encode (
array(
"status"=>'false',
//"Seller Details"=>$query->result(),
));
}else{
//$this->response("success", 200);
echo json_encode (
array(
"status"=>'true',
"message"=>'Customer Registered Successfully',
//"Seller Details"=>$result->result(),
));
}
}
}
if the functions customer_phoneno_check & customer_email_check at Model_Api.php returns false i need to show the response saying already exist which is at ../controllers/Api.php using function customer_register_api()
Table : customers_info
Keys : customer_email & customer_phone_no
Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.
I created a new column in the "sales_flat_order" table called "gc_sent", default value of 0.
From here, I'm trying to perform an if statement below in the code, saying if the Card's gc_sent is 0, then send an email to the customer with their giftcard in it. Then set the card_status to 1, and gc_sent to 1.
However, what I'm running into in my dev environment, I'm receiving email after email, 1 per minute, with my gift card information in it. That shouldn't be happening. That's what I'm trying to prevent. That's why I'm doing conditions including curDate (current date), and MailDeliveryDate. To ensure that everything jives.
So, what am I doing wrong? What do I need to change? I'm relatively new to Magento, only been doing it for a few months now, by the way.
The most relevant section is:
$curDate = date('Y-m-d');
$cards = Mage::getModel('giftcards/giftcards')->getCollection()
->addFieldToFilter('order_id', $order->getId())
->addFieldToFilter('gc_sent', 0);
foreach($cards as $card) {
if (($card->getGcSent() == 0) && ($curDate == $card->getMailDeliveryDate())) {
if ((($card->getMailDeliveryDate() == null) || ($curDate == $card->getMailDeliveryDate())) && $card->getCardType() != 'offline') {
$this->_send($post, 'giftcards/email/email_template', $mail, $storeId);
$card->setCardStatus(1)->save();
$order->setGcSent(1)->save();
}
}
}
But this is the complete code:
<?php
class Sportys_Giftcardoverride_Model_Giftcards extends Webtex_Giftcards_Model_Giftcards
{
protected function _sendEmailCard($storeId = 0)
{
if($order = Mage::getModel('sales/order')->load($this->getOrderId())){
$storeId = $order->getStoreId();
} else {
$storeId = 1;
}
$amount = number_format(Mage::app()->getStore($storeId)->convertPrice($this->getCardAmount(), false, false),2);
if(Mage::helper('giftcards')->isUseDefaultPicture() || !$this->getProductId()) {
$picture = Mage::getDesign()->getSkinUrl('images/giftcard.png',array('_area'=>'frontend'));
} else {
$product = Mage::getModel('catalog/product')->load($this->getProductId());
if (!$product->getId() || $product->getImage() != 'no_selection') {
$picture = Mage::helper('catalog/image')->init($product, 'image');
} else {
$picture = Mage::getDesign()->getSkinUrl('images/giftcard.png',array('_area'=>'frontend'));
}
}
//Change picture if one is found in picture array
$cardDesigns = __DIR__ . '/../../../../../../sportysadmin/giftcarddesigns.php';
if(file_exists($cardDesigns)){
include $cardDesigns;
}
$post = array(
'amount' => $this->_addCurrencySymbol($amount,$this->getCardCurrency()),
'code' => $this->getCardCode(),
'email-to' => $this->getMailTo(),
'email-from' => $this->getMailFrom(),
'recipient' => $this->getMailToEmail(),
'email-message' => nl2br($this->getMailMessage()),
'store-phone' => Mage::getStoreConfig('general/store_information/phone'),
'picture' => $picture,
);
$mail = trim($this->getMailToEmail()) ;
if(empty($mail)) {
$mail = $order->getCustomerEmail() ;
}
$curDate = date('Y-m-d');
$cards = Mage::getModel('giftcards/giftcards')->getCollection()
->addFieldToFilter('order_id', $order->getId())
->addFieldToFilter('gc_sent', 0);
foreach($cards as $card) {
if (($card->getGcSent() == 0) && ($curDate == $card->getMailDeliveryDate())) {
if ((($card->getMailDeliveryDate() == null) || ($curDate == $card->getMailDeliveryDate())) && $card->getCardType() != 'offline') {
$this->_send($post, 'giftcards/email/email_template', $mail, $storeId);
$card->setCardStatus(1)->save();
$order->setGcSent(1)->save();
}
}
}
}
protected function _send($post, $template, $email, $storeId)
{
if ($email) {
$translate = Mage::getSingleton('core/translate');
$translate->setTranslateInline(false);
$postObject = new Varien_Object();
$postObject->setData($post);
$postObject->setStoreId($storeId);
$mailTemplate = Mage::getModel('core/email_template');
$pdfGenerator = new Webtex_Giftcards_Model_Email_Pdf();
//$this->_addAttachment($mailTemplate, $pdfGenerator->getPdf($postObject), 'giftcard.pdf');
$mailTemplate->setDesignConfig(array('area' => 'frontend', 'store' => $storeId))
->sendTransactional(
Mage::getStoreConfig($template, $storeId),
'general',
$email,
null,
array('data' => $postObject)
);
$translate->setTranslateInline(true);
} else {
throw new Exception('Invalid recipient email address.');
}
}
}
?>
the problem is in your below code
if ((($card->getMailDeliveryDate() == null) || ($curDate == $card->getMailDeliveryDate())) && $card->getCardType() != 'offline') {
$this->_send($post, 'giftcards/email/email_template', $mail, $storeId);
$card->setCardStatus(1)->save();
$order->setGcSent(1)->save();
}
you are setting setGcSent(1) on $order instead of $card try changing that code to
$card->setCardStatus(1)
->setGcSent(1)
->save();
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();
}
If my value is equal to null then I want to assign the value of 0 instead of having null. I've achieved that using my if statement however, its a lot of code production and I plan on adding more social networks is there a better way of achieving this.
$google = $request->input('google');
$facebook = $request->input('facebook');
if ($request->input('google') == null){
$google = 0;
} else {
$google = 1;
}
if ($request->input('facebook') == null){
$facebook = 0;
} else {
$facebook = 1;
}
You can use trenary operator
$google = ($request->input('google') == null) ? 0 : 1;
In order to prevent repeating the same code for each social networks you can do this.
$providers = array(
'google',
'facebook',
);
foreach ($providers as $provider) {
if ($request->input($provider) == null) {
$$provider = 0;
} else {
$$provider = 1;
}
}
IMO the drawback is creating a dynamic variable name, to prevent this, you need to some modifications :
$providers = array(
'google' => 0,
'facebook' => 0,
);
foreach ($providers as $providerKey => $providerValue) {
if ($request->input($providerKey) != null) {
$providers[$providerKey] = 1;
}
}
Hope this helps