CI3 hook only work on local but not on server - php

So my team have cloned a project that have a hook that can track the activity of the users like anything that they POST or GET. The previous project have work perfectly on local and on server. But on the recent project, it only work normal when I run it on local. But on server the hook only track user when they log out.
here's the hooks.php "application/config":
$hook['post_controller_constructor'][] = array(
'class' => 'Activity_user',
'function' => 'log_activity',
'filename' => 'log_activity_user.php',
'filepath' => 'hooks',
// 'params' => array('red', 'yellow', 'blue')
);
here's the log_activity_user "application/hooks/":
class Activity_user {
function __construct() {
$this->CI =& get_instance();
$this->CI->load->library('session');
$this->CI->load->library('lactivityuser');
}
public function log_activity() {
$post = $this->CI->input->post();
$get = $this->CI->input->get();
$timezone = new DateTimeZone('Asia/Jakarta');
$date = new DateTime();
$date->setTimeZone($timezone);
$result = $date->format('Y-m-d H:i:s');
if(count($post) > 0){
if (strpos($_SERVER["REQUEST_URI"], '/login')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'melakukan login',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/Log_data')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat Log Data',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/History_IO')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat History IO',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/Dashboard')) {
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Melihat Dashboard',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/api/rule')) {
$data = array(
'email' => ' ',
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Rule',
'created_date' => $result,
);
}else if (strpos($_SERVER["REQUEST_URI"], '/API/Rule')) {
$data = array(
'email' => ' ',
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => 'Rule',
'created_date' => $result,
);
}
else{
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => json_encode($post),
'created_date' => $result,
);
}
$this->CI->db->insert('tb_activity_user', $data);
}else if(count($get) > 0){
$data = array(
'email' => $_SESSION["email"] ?? $post["email"],
'menu_name' => $_SERVER["REQUEST_URI"],
'activity' => json_encode($get),
'created_date' => $result,
);
$this->CI->db->insert('tb_activity_user', $data);
}
}
}
edit: they have enable the hook to TRUE in the config file

Related

Fedex API Rate request issues, php

I can't figure out what I'm doing wrong I've set the authentication and version number but I just can get authenticated.
I get the following error when I try the sample code.
Severity: ERROR
Source: prof
Code: 1000
Message: Authentication Failed
Can anyone advise me on this please?! This is the first part of code, which is a barely modified copy of the example.
$path_to_wsdl = "./RateService_v18.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => 'PmzmlFAKEKEYVha',
'Password' => 'myfedex-website-password'
)
);
$request['ClientDetail'] = array(
'AccountNumber' => '123456789',
'MeterNumber' => '123456789'
);
$request['TransactionDetail'] = array('CustomerTransactionId' => 'testing');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '18',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
$request['RequestedShipment']['TotalInsuredValue']=array('Ammount'=>100,'Currency'=>'USD');
$request['RequestedShipment']['Shipper'] = addShipper();
$request['RequestedShipment']['Recipient'] = addRecipient();
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['RateRequestTypes'] = 'ACCOUNT';
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1();
try
{
if(setEndpoint('changeEndpoint'))
{
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}
$response = $client ->getRates($request);
if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR')
{
$rateReply = $response -> RateReplyDetails;
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>';
$serviceType = '<td>'.$rateReply -> ServiceType . '</td>';
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
if(array_key_exists('DeliveryTimestamp',$rateReply)){
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td> </td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';
echo '</table>';
printSuccess($client, $response);
}
else
{
printError($client, $response);
}
writeToLog($client); // Write to log file
} catch (SoapFault $exception) {
printFault($exception, $client);
}
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Collierville',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38017',
'CountryCode' => 'US')
);
return $shipper;
}
function addRecipient(){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => 'Richmond',
'StateOrProvinceCode' => 'BC',
'PostalCode' => 'V7C4V4',
'CountryCode' => 'CA',
'Residential' => false)
);
return $recipient;
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US')
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF', // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75');
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array('Currency' => 'USD', 'Amount' => 150),
'CollectionType' => 'ANY')// ANY, GUARANTEED_FUNDS
);
return $specialServices;
}
function addPackageLineItem1(){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => 50.0,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => 108,
'Width' => 5,
'Height' => 5,
'Units' => 'IN'
)
);
return $packageLineItem;
}
Thank you in advance for ANY help! :)
the password is not your password you already have. it is another one they email you later. :/

Prestashop HelpForm type switch in module

I want create a input type switch in my backend module in prestashop 1.6.
I write this and work
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => true,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'active_on',
'value' => true,
'label' => $this->l('Enabled')
),
array(
'id' => 'active_off',
'value' => false,
'label' => $this->l('Disabled')
)
),
)
But if i try with custom value e not boolean it not work
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => false,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'value1',
'value' => 'value1',
'label' => $this->l('value1')
),
array(
'id' => 'value2',
'value' => 'value2',
'label' => $this->l('value2')
)
),
)
In backend appear two boxes with labels value 'no'.
In HelperForm classes of prestashop there is no trace of input type switch.
The same code with type radio work, but i want a switch type.
Unfortunately, as you can see here:
PrestaShop doesn't have possibility to use custom value in "switch" field.
You don't need to change default switch values.
This is how you handle submit form:
public function getContent()
{
if (Tools::isSubmit('submitForm'))
{
$my_value = ( (int)Tools::getValue('PRESTASHOP_INPUT_SWITCH') == 1 ) ? 'value1' : 'value2';
if (Configuration::updateValue('PRESTASHOP_INPUT_SWITCH', $my_value))
$echo .= $this->displayConfirmation($this->l('Value updated.'));
}
$echo .= $this->renderForm();
return $echo;
}
You probably already have something like this:
public function renderForm()
{
$fields_form = array(
'form' => array(
'legend' => array(
'title' => $this->l('Settings'),
'icon' => 'icon-cogs'
),
'input' => array(
array(
'type' => 'switch',
'label' => $this->l('Label'),
'name' => 'PRESTASHOP_INPUT_SWITCH',
'is_bool' => true,
'desc' => $this->l('Description'),
'values' => array(
array(
'id' => 'active_on',
'value' => 1,
'label' => $this->l('Value1')
),
array(
'id' => 'active_off',
'value' => 0,
'label' => $this->l('Value2')
)
),
)
),
'submit' => array(
'title' => $this->l('Save'),
)
),
);
$helper = new HelperForm();
$helper->module = $this;
$helper->show_toolbar = false;
$helper->table = $this->table;
$lang = new Language((int)Configuration::get('PS_LANG_DEFAULT'));
$helper->default_form_language = $lang->id;
$helper->allow_employee_form_lang = Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') ? Configuration::get('PS_BO_ALLOW_EMPLOYEE_FORM_LANG') : 0;
$this->fields_form = array();
$helper->identifier = $this->identifier;
$helper->submit_action = 'submitForm';
$helper->currentIndex = $this->context->link->getAdminLink('AdminModules', false).'&configure='.$this->name.'&tab_module='.$this->tab.'&module_name='.$this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->tpl_vars = array(
'fields_value' => $this->getConfigFieldsValues(),
'languages' => $this->context->controller->getLanguages(),
'id_language' => $this->context->language->id
);
return $helper->generateForm(array($fields_form));
}
and loading the values:
public function getConfigFieldsValues()
{
return array(
'PRESTASHOP_INPUT_SWITCH' => Tools::getValue('PRESTASHOP_INPUT_SWITCH', Configuration::get('PRESTASHOP_INPUT_SWITCH') == 'value1' : 1 : 0),
);
}
Unfortunately prestashop doesn't support the custom value of switch but you can handle this like:
$config = Configuration::get('oneclickcheckout');
$this->settings = Tools::unSerialize($config);
$settings = $this->settings;
if (isset($settings['Description']) && $settings['Description'] == 1) {
}

Prestashop custom field in Product Feature not saving on Edit

I have created a custom field for Product Feature in my module override. Custom field for Feature is not saving in the database on edit. But on Add new feature it works fine. Here is the code for my AdminFeaturesController.php file:
<?php
class AdminFeaturesController extends AdminFeaturesControllerCore
{
public function __construct()
{
$this->table = 'feature';
$this->className = 'Feature';
$this->list_id = 'feature';
$this->identifier = 'id_feature';
$this->lang = true;
$this->fields_list = array(
'id_feature' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'name' => array(
'title' => $this->l('Name'),
'width' => 'auto',
'filter_key' => 'b!name'
),
'value' => array(
'title' => $this->l('Values'),
'orderby' => false,
'search' => false,
'align' => 'center',
'class' => 'fixed-width-xs'
),
'parent_id_feature' => array(
'title' => $this->l('ParentID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'position' => array(
'title' => $this->l('Position'),
'filter_key' => 'a!position',
'align' => 'center',
'class' => 'fixed-width-xs',
'position' => 'position'
)
);
$this->bulk_actions = array(
'delete' => array(
'text' => $this->l('Delete selected'),
'icon' => 'icon-trash',
'confirm' => $this->l('Delete selected items?')
)
);
AdminController::__construct();
}
/**
* AdminController::renderForm() override
* #see AdminController::renderForm()
*/
public function renderForm()
{
$this->toolbar_title = $this->l('Add a new feature');
$this->fields_form = array(
'legend' => array(
'title' => $this->l('Feature with Parent'),
'icon' => 'icon-info-sign'
),
'input' => array(
array(
'type' => 'text',
'label' => $this->l('Name'),
'name' => 'name',
'lang' => true,
'size' => 33,
'hint' => $this->l('Invalid characters:').' <>;=#{}',
'required' => true
),
array(
'type' => 'select',
'label' => $this->l('Parent Feature'),
'name' => 'parent_id_feature',
'options' => array(
'query' => Feature::getFeaturesExcept($this->context->language->id, Tools::getValue('id_feature')),
'id' => 'id_feature',
'name' => 'name'
),
'required' => true
)
)
);
if (Shop::isFeatureActive())
{
$this->fields_form['input'][] = array(
'type' => 'shop',
'label' => $this->l('Shop association'),
'name' => 'checkBoxShopAsso',
);
}
$this->fields_form['submit'] = array(
'title' => $this->l('Save'),
);
return AdminController::renderForm();
}
public function renderView()
{
if (($id = Tools::getValue('id_feature')))
{
$this->setTypeValue();
$this->list_id = 'feature_value';
$this->position_identifier = 'id_feature_value';
$this->position_group_identifier = 'id_feature';
$this->lang = true;
// Action for list
$this->addRowAction('edit');
$this->addRowAction('delete');
if (!Validate::isLoadedObject($obj = new Feature((int)$id)))
{
$this->errors[] = Tools::displayError('An error occurred while updating the status for an object.').'
<b>'.$this->table.'</b> '.Tools::displayError('(cannot load object)');
return;
}
$this->feature_name = $obj->name;
$this->toolbar_title = $this->feature_name[$this->context->employee->id_lang];
$this->fields_list = array(
'id_feature_value' => array(
'title' => $this->l('ID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'value' => array(
'title' => $this->l('Value')
),
'parent_id_feature_value' => array(
'title' => $this->l('ParentID'),
'align' => 'center',
'class' => 'fixed-width-xs'
),
'position' => array(
'title' => $this->l('Position'),
'filter_key' => 'a!position',
'align' => 'center',
'class' => 'fixed-width-xs',
'position' => 'position'
)
);
$this->_where = sprintf('AND `id_feature` = %d', (int)$id);
$this->_orderBy = 'position';
self::$currentIndex = self::$currentIndex.'&id_feature='.(int)$id.'&viewfeature';
$this->processFilter();
return AdminController::renderList();
}
}
/**
* AdminController::renderForm() override
* #see AdminController::renderForm()
*/
public function initFormFeatureValue()
{
$this->setTypeValue();
$parent_id = Feature::getParentFeatureID((int)Tools::getValue('id_feature'));
$this->fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Feature value'),
'icon' => 'icon-info-sign'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Feature'),
'name' => 'id_feature',
'options' => array(
'query' => Feature::getFeatures($this->context->language->id),
'id' => 'id_feature',
'name' => 'name'
),
'required' => true
),
array(
'type' => 'text',
'label' => $this->l('Value'),
'name' => 'value',
'lang' => true,
'size' => 33,
'hint' => $this->l('Invalid characters:').' <>;=#{}',
'required' => true
),
array(
'type' => 'select',
'label' => $this->l('Parent Feature Value'),
'name' => 'parent_id_feature_value',
'options' => array(
'query' => FeatureValue::getFeatureValuesWithLang($this->context->language->id, $parent_id),
'id' => 'id_feature_value',
'name' => 'value'
),
'required' => true
),
),
'submit' => array(
'title' => $this->l('Save'),
),
'buttons' => array(
'save-and-stay' => array(
'title' => $this->l('Save then add another value'),
'name' => 'submitAdd'.$this->table.'AndStay',
'type' => 'submit',
'class' => 'btn btn-default pull-right',
'icon' => 'process-icon-save'
)
)
);
$this->fields_value['id_feature'] = (int)Tools::getValue('id_feature');
// Create Object FeatureValue
$feature_value = new FeatureValue(Tools::getValue('id_feature_value'));
$this->tpl_vars = array(
'feature_value' => $feature_value,
);
$this->getlanguages();
$helper = new HelperForm();
$helper->show_cancel_button = true;
$back = Tools::safeOutput(Tools::getValue('back', ''));
if (empty($back))
$back = self::$currentIndex.'&token='.$this->token;
if (!Validate::isCleanHtml($back))
die(Tools::displayError());
$helper->back_url = $back;
$helper->currentIndex = self::$currentIndex;
$helper->token = $this->token;
$helper->table = $this->table;
$helper->identifier = $this->identifier;
$helper->override_folder = 'feature_value/';
$helper->id = $feature_value->id;
$helper->toolbar_scroll = false;
$helper->tpl_vars = $this->tpl_vars;
$helper->languages = $this->_languages;
$helper->default_form_language = $this->default_form_language;
$helper->allow_employee_form_lang = $this->allow_employee_form_lang;
$helper->fields_value = $this->getFieldsValue($feature_value);
$helper->toolbar_btn = $this->toolbar_btn;
$helper->title = $this->l('Add a new feature value');
$this->content .= $helper->generateForm($this->fields_form);
}
public function ajaxProcessUpdatePositions()
{
if ($this->tabAccess['edit'] === '1')
{
$way = (int)Tools::getValue('way');
$id = (int)Tools::getValue('id');
$table = 'feature';
$positions = Tools::getValue($table);
if (empty($positions))
{
$table = 'feature_value';
$positions = Tools::getValue($table);
}
$new_positions = array();
foreach ($positions as $v)
if (!empty($v))
$new_positions[] = $v;
foreach ($new_positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id)
{
if ($table == 'feature')
{
if ($feature = new Feature((int)$pos[2]))
if (isset($position) && $feature->updatePosition($way, $position, $id))
echo 'ok position '.(int)$position.' for feature '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update feature '.(int)$id.' to position '.(int)$position.' "}';
else
echo '{"hasError" : true, "errors" : "This feature ('.(int)$id.') can t be loaded"}';
break;
}
elseif ($table == 'feature_value')
{
if ($feature_value = new FeatureValue((int)$pos[2]))
if (isset($position) && $feature_value->updatePosition($way, $position, $id))
echo 'ok position '.(int)$position.' for feature value '.(int)$pos[2].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update feature value '.(int)$id.' to position '.(int)$position.' "}';
else
echo '{"hasError" : true, "errors" : "This feature value ('.(int)$id.') can t be loaded"}';
break;
}
}
}
}
}
}
And my Feature.php is:
<?php
class Feature extends FeatureCore
{
/** #var string Name */
public $parent_id_feature;
/**
* #see ObjectModel::$definition
*/
public static $definition = array(
'table' => 'feature',
'primary' => 'id_feature',
'multilang' => true,
'fields' => array(
'position' => array('type' => self::TYPE_INT, 'validate' => 'isInt'),
// Parent Feature ID
'parent_id_feature' => array('type' => self::TYPE_INT, 'validate' => 'isUnsignedId', 'required' => false),
// Lang fields
'name' => array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128),
)
);
/**
* Get a parent feature id for a given id_feature
*
* #param integer $id_feature Feature id
* #return integer ID of parent feature
* #static
*/
public static function getParentFeatureID($id_feature)
{
return Db::getInstance()->getValue('
SELECT parent_id_feature
FROM `'._DB_PREFIX_.'feature` f
WHERE f.`id_feature` = '.(int)$id_feature
);
}
/**
* Get all features for a given language except for given id
*
* #param integer $id_lang Language id
* #param integer $id_feature Feature id to exclude
* #return array Multiple arrays with feature's data
* #static
*/
public static function getFeaturesExcept($id_lang, $id_feature, $with_shop = true)
{
return Db::getInstance()->executeS('
SELECT DISTINCT f.id_feature, f.*, fl.*
FROM `'._DB_PREFIX_.'feature` f
'.($with_shop ? Shop::addSqlAssociation('feature', 'f') : '').'
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON (f.`id_feature` = fl.`id_feature` AND fl.`id_lang` = '.(int)$id_lang.')
WHERE f.id_feature != '.(int)$id_feature.'
ORDER BY f.`position` ASC');
}
}

Fedex api returns this error array(0) { }?

I am using Codeigniter library to get fedex rates i have created my own library to get rates and i grab data on my controller the request processes but its returns me array(0) { } error, i have searched a lot i can't find why it returns array 0 what is this error what i am doing wrong.
My library file.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class fedex{
function rates(){
$weight = '46';
$this->path_to_wsdl = base_url()."assets/wsdl/RateService_v14.wsdl";
$key = 'acess_key';
$password = 'password';
$shipAccount = 'accound_no';
$meter = 'meter_no';
$dropofftype = 'dropofftype';
$service = 'FEDEX_1_DAY_FREIGHT';
$package = 'package';
$handling_method = 'price';
$handling_amount = '5';
$pkg_width = '6';
$pkg_height = '6';
$pkg_length = '5';
$insurance = true;
$billAccount = $shipAccount;
// Build Request
$package = $this->package_types['FEDEX_10KG_BOX'] = 'FEDEX_10KG_BOX';
$dropofftype = $this->dropoff_types['REGULAR_PICKUP'] = 'REGULAR_PICKUP';
ini_set("soap.wsdl_cache_enabled", 0);
ini_set('soap.wsdl_cache_ttl',0);
$client = new SoapClient($this->path_to_wsdl, array('trace' => 1, "exception" => 0));
// Refer to http://us3.php.net/manual/en/ref.soap.php for more information
$request['WebAuthenticationDetail'] = array(
'UserCredential' =>array(
'Key' => $key,
'Password' => $password
)
);
$request['ClientDetail'] = array(
'AccountNumber' => $shipAccount,
'MeterNumber' => $meter
);
$request['TransactionDetail'] = array('CustomerTransactionId' => '*** Rate Request v14 using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs',
'Major' => '14',
'Intermediate' => '0',
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = false;
$request['RequestedShipment']['RequestedCurrency'] ='$';
$request['RequestedShipment']['DropoffType'] = $dropofftype;
$request['RequestedShipment']['ShipTimestamp'] = date('c');
$request['RequestedShipment']['PackagingType'] = $package;
if($insurance=='yes')
{
$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=> '5',
'Currency'=> '$',
);
}
$request['RequestedShipment']['Shipper'] = array(
'Contact' => array(
'CompanyName' => 'companyname',
'EMailAddress' => 'EMailAddress'
),
'Address' => array(
'StreetLines' => 'StreetLines',
'City' => 'City',
'StateOrProvinceCode' => 'StateOrProvinceCode',
'PostalCode' => 'PostalCode',
'CountryCode' => 'CountryCode'
)
);
$request['RequestedShipment']['Recipient'] = array(
'Contact' => array(
'PersonName' => " ",
'CompanyName' => '',
'PhoneNumber' => '',
),
'Address' => array(
'StreetLines' => '',
'City' => '',
'StateOrProvinceCode' => '',
'PostalCode' => 'postalcode',
'CountryCode' => '',
//'Residential' => false // no way to determine this
)
);
$request['RequestedShipment']['RateRequestTypes'] = 'LIST';
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => $weight,
'Units' => 'lbs'
),
'Dimensions' => array(
'Length' => $pkg_length,
'Width' => $pkg_width,
'Height' => $pkg_height,
'Units' => 'feet'
)
);
// Send the request to FedEx
$response = $client->getRates($request);
// Handle response
if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR' )
{
if(!is_array(#$response->RateReplyDetails))
{
return array(); // No Results
}
foreach ($response->RateReplyDetails as $rateReply)
{
if(in_array($rateReply->ServiceType, $service))
{
$amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
if(is_numeric($handling_amount)) // valid entry?
{
if($handling_method=='price')
{
$amount += $handling_amount;
}
elseif($handling_method=='percent')
{
$amount += $amount * ($handling_amount/100);
}
}
$rates[$this->service_list[$rateReply->ServiceType]] = number_format($amount,2,".",",");
}
}
return $rates;
}
else
{
return array(); // fail
}
}
}
My controller.
public function fedex(){
$this->load->library('fedex/fedex');
$fedex = new Fedex;
$weight = 46;
$dest_zip = '10001';
$fexed_rates = $fedex->rates();
var_dump($fexed_rates); die;
}
from the last you can see the line
Error Line No : $amount = $rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount;
Correct:
$amount = $rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount;

Create an multidimensional array from a database table

I have a mysql table which contains is:
folder_id (int(11), auto increment)
folder_name (varchar)
folder_class(varchar)
folder_link (varchar)
What I want to do is somehow loop through the table and store each row like this:
$packs = array( array( 'Name' => 'DarkUIPack',
'Class' => 'ui',
'Link' => 'http://graphicriver.net/item/dark-minimalist-ui-pack/662762'
),
array( 'Name' => 'MinimalistIcons',
'Class' => 'min',
'Link' => 'http://graphicriver.net/item/small-minimalist-icons-pack/670469'
),
array( 'Name' => 'BlueMediaIcons',
'Class' => 'blue',
'Link' => 'http://graphicriver.net/item/blue-media-icons-set/705319'
),
array( 'Name' => 'MediaIcons',
'Class' => 'med',
'Link' => 'http://graphicriver.net/item/media-icons-set/679835'
),
array( 'Name' => 'ToTheTopButtons',
'Class' => 'top',
'Link' => 'http://graphicriver.net/item/to-the-top-buttons/673221'
),
array( 'Name' => 'Sunglasses',
'Class' => 'sun',
'Link' => ''
),
array( 'Name' => 'RealEstate',
'Class' => 'est',
'Link' => 'http://graphicriver.net/item/simple-real-estate-logo/724697'
),
array( 'Name' => 'PhotoStudio',
'Class' => 'std',
'Link' => 'http://graphicriver.net/item/photo-studio-logo/724694'
),
array( 'Name' => 'PayDayCity',
'Class' => 'std',
'Link' => ''
),
array( 'Name' => 'MoleculeCorp',
'Class' => 'mol',
'Link' => 'http://graphicriver.net/item/molecule-corp-logo/719307'
),
array( 'Name' => 'ClubbGX',
'Class' => 'gx',
'Link' => ''
),
array( 'Name' => 'AerialVision',
'Class' => 'aer',
'Link' => ''
),
array( 'Name' => 'ServiceCompany',
'Class' => 'ser',
'Link' => 'http://graphicriver.net/item/service-company-logo/727091'
),
array( 'Name' => 'ElectroTech',
'Class' => 'ele',
'Link' => 'http://graphicriver.net/item/electro-tech-logo/720904'
),
array( 'Name' => 'CreativeStudio',
'Class' => 'cre',
'Link' => 'http://graphicriver.net/item/creative-studio-logo/719494'
),
array( 'Name' => 'NanoCorp',
'Class' => 'nan',
'Link' => 'http://graphicriver.net/item/nano-corp-logo/719098'
),
array( 'Name' => 'RehabPlace',
'Class' => 'reh',
'Link' => ''
),
array( 'Name' => 'MyLocalMix',
'Class' => 'mix',
'Link' => ''
),
array( 'Name' => 'SevenBySeven',
'Class' => 'sev',
'Link' => ''
),
array( 'Name' => 'ComingSoon',
'Class' => 'com',
'Link' => ''
),
array( 'Name' => 'AlienIcons',
'Class' => 'aln',
'Link' => 'http://graphicriver.net/item/alien-icons-set/698515'
),
array( 'Name' => 'PreloaderPortfolio',
'Class' => 'pre',
'Link' => ''
),
array( 'Name' => 'BioTech',
'Class' => 'bio',
'Link' => ''
),
array( 'Name' => 'ConstructionCompany',
'Class' => 'con',
'Link' => ''
),
array( 'Name' => 'EagleMedia',
'Class' => 'egl',
'Link' => ''
),
array( 'Name' => 'ElectronicWays',
'Class' => 'elw',
'Link' => ''
),
array( 'Name' => 'EnvironmentalCompany',
'Class' => 'env',
'Link' => ''
),
array( 'Name' => 'SecureData',
'Class' => 'sec',
'Link' => 'http://graphicriver.net/item/secure-data-company-logo/907334'
),
array( 'Name' => 'ConstructSimple',
'Class' => 'cns',
'Link' => 'http://graphicriver.net/item/simple-construction-company-logo/907538'
),
array( 'Name' => 'ConstructRoof',
'Class' => 'cnr',
'Link' => 'http://graphicriver.net/item/construction-company-logo/907549'
)
);
where 'Name' corresponds to folder_name, 'Class' to folder_class and 'Link' to folder_link.
I'm using this within a class and the class looks like this till now:
class folder
{
private $connect;
public function __construct() {
$this->connect = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if (mysqli_connect_errno()) {
$error = true;
$message['error'] = true;
$message['message'] = mysqli_connect_error();
return json_encode($message);
}
else {
return true;
}
}
public function crtFolder($fldName,$fldClass,$fldLink,$fldPath) {
$fldName = preg_replace('/\s+/', '', $fldName);
$fldPN = $fldPath."\\".$fldName;
$modArray = array(array('1'));
if ((!is_dir($fldPN))) {
if(mkdir($fldPN,0777,true)) {
$sql = "INSERT INTO folders (folder_name,folder_class,folder_link) VALUES (?, ?, ?)";
if($stmt = $this->connect->prepare($sql)) {
$stmt->bind_param("sss", $fldName, $fldClass, $fldLink);
$stmt->execute();
$stmt->close();
$error = false;
$message['error'] = false;
$message['message'] = "Folder Created | Data Successfuly Inserted";
return json_encode($message);
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "Folder Created | Data Failed To Insert";
return json_encode($message);
}
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "Folder Failed To Create";
return json_encode($message);
}
}
else {
$error = true;
$message['error'] = true;
$message['message'] = "Folder Already Exists";
return json_encode($message);
}
}
public function __destruct() {
$closeConnection = $this->connect->close();
if($closeConnection) {
return true;
}
}
}
I'm showing the class because I want to keep the same method for the creating the array as the other methods are created. Because I found something on Google, but it was making an array from multiple tables. I only have one table.
Write below given function in to your class. Hope this will help things.
public function getTableData(){
$sql = "SELECT * FROM folders";
if($stmt = $this->connect->prepare($sql)) {
$stmt->execute();
$stmt->close();
$arrFinalArray = array();
while ($arrFolder = $stmt->fetch()){
$arrFinalArray[] = array(
'Name' => $arrFolder['folder_name'],
'Class' => $arrFolder['folder_class'],
'Link' => $arrFolder['folder_link']
);
}
}
}
Following your format:
if($stmt = $this->connect->prepare($sql)) {
$stmt->bind_param("sss", $fldName, $fldClass, $fldLink);
$stmt->execute();
$result = array();
while ($stmt->fetch()) {
$result[] = array('Name' => $fldName, 'Class' => $fldClass, 'Link' => $fldLink);
}
print_r($result);
}
It should work.
Try something like this :
$result = SOMETHING_FROM_QUERY;
$packs = new array();
while ($row = mysql_fetch_assoc($result)) {
array_push($packs,array('Name' => $row['folder_name'], 'Class' => $row['folder_class'], 'Link' => $row['folder_link']));
}

Categories