getting multiple customer details In codeigniter - php

i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}

Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}

Related

Download files from external url in Laravel/PHP

I want to download files using external urls on click below code i am using and its working fine now error but file is not downloading anywhere.
public function checkCount(Request $request)
{
$userid = Session::get('UserId');
$count = DB::table('download_details')
->where('type','=',$request->type)
->where('user_id','=',$userid)
->get()
// echo "<pre>"; print_r($count); die;
->count();
if($count >= 2)
{
echo 0;
}
else
{
$data = array(
'corporate_id' => $request->corporateid,
'user_id' => Session::get('UserId'),
'ip_address' => \Request::ip(),
'mac_address' => '',
'type' => $request->type,
'count' => '',
'date' => date('Y-m-d'),
'status' => 1
);
$insert = DB::table('download_details')->insert($data);
$name = basename($request->url);
$path = $request->url;
// echo $path; die;
$tempImage = tempnam(sys_get_temp_dir(), $path);
copy($request->url, $tempImage);
return response()->download($tempImage, $name);
}
}
My Ajax Code
function saveData(type,url)
{
var corporateid = $('#corporateid').val();
// alert(type);
$.ajax({
type:'POST',
url:'/check-count',
data:{'_token':'{{csrf_token()}}',corporateid:corporateid,type:type,url:url},
success:function(response){
// alert(response);
if(response == 0)
{
$('#download_error_message').show();
$('#download_error_message').html("Download Limit Exceeded");
$('#download_error_message').fadeOut(4000);
}
else
{
alert("Success");
}
}
});
}
Else part shows that i am downloading file. NO errors is ajax request but file is not downloading at all.
file is not downloading.please help
Hopefully, it will work.
public function checkCount(Request $request)
{
$userid = Session::get('UserId');
$count = DB::table('download_details')
->where('type','=',$request->type)
->where('user_id','=',$userid)
->get()
// echo "<pre>"; print_r($count); die;
->count();
if($count >= 2)
{
echo 0;
}
else
{
$data = array(
'corporate_id' => $request->corporateid,
'user_id' => Session::get('UserId'),
'ip_address' => \Request::ip(),
'mac_address' => '',
'type' => $request->type,
'count' => '',
'date' => date('Y-m-d'),
'status' => 1
);
$insert = DB::table('download_details')->insert($data);
$name = basename($request->url);
$path = $request->url;
// echo $path; die;
$tempImage = tempnam(sys_get_temp_dir(), $path);
copy($request->url, $tempImage);
$mimeType = mime_content_type($tempImage);
$headers = ["Content-Type: {$mimeType}"];
return Response::download($tempImage, $name, $headers);
}
}

Creating default object from empty value through an array

I have read multiple threads here about the matter, although none of the solutions seem to be similar to mine. I would have attempted to fix this myself but unable to find anything similar I don't even know where to begin. Why am I getting this error, and what are the proper steps to resolve it?
function handleRequestsave_details()
{
$this->vbulletin->input->clean_array_gpc('p', array('fullname' => TYPE_STR,
'address_1' => TYPE_STR, 'address_2' => TYPE_STR, 'address_city' => TYPE_STR,
'address_state' => TYPE_STR, 'address_zip' => TYPE_STR, 'country' => TYPE_STR,
'phone' => TYPE_STR, 'company' => TYPE_STR));
if ($this->checkDetailsFields('details', $this->vbphrase['memarea_required_fields']))
{
$information = $this->buildInfoArray();
$this->vbulletin->userinfo['ma_info'] = $information;
$this->vbulletin->userinfo['usergroupid'] = $usergrpid;
if ($this->setCustomerNumber($information, $usergrpid))
{
$vbulletin->url = 'members.php?' . $vbulletin->session->vars['sessionurl'] . "do=details";
eval(print_standard_redirect('memarea_saved_details', true, true));
}
}
}
Here are the other functions included in this script, This is not my code it is simply an old product for vBulletin 3.x I am trying to update for my site. this portion throwing the error is when customers enter their billing details to save in their profile.
function checkDetailsFields($requested, $errormessage)
{
if (empty($this->vbulletin->GPC['fullname']) or empty($this->vbulletin->GPC['address_1']) or
empty($this->vbulletin->GPC['address_city']) or empty($this->vbulletin->GPC['address_zip']) or
empty($this->vbulletin->GPC['country']) or empty($this->vbulletin->GPC['phone']))
{
//$GLOBALS['error'] = $errormessage;
eval(standard_error($errormessage));
//$this->handleRequest($requested);
return false;
}
return true;
}
function buildInfoArray()
{
return array('fullname' => $this->vbulletin->GPC['fullname'], 'address_1' => $this->
vbulletin->GPC['address_1'], 'address_2' => $this->vbulletin->GPC['address_2'],
'address_city' => $this->vbulletin->GPC['address_city'], 'address_state' => $this->
vbulletin->GPC['address_state'], 'address_zip' => $this->vbulletin->GPC['address_zip'],
'country' => $this->vbulletin->GPC['country'], 'phone' => $this->vbulletin->GPC['phone'],
'company' => $this->vbulletin->GPC['company']);
}
function setCustomerNumber($ma_info, $usergroup = '', $usevb = true, $userinfo = '')
{
if ($usevb == false)
{
$this->vbulletin->userinfo = &$userinfo;
}
$fcust = $this->fields['custnum'];
$fpass = $this->fields['mpassword'];
$finfo = $this->fields['info'];
$userdm = datamanager_init('User', $this->vbulletin, ERRTYPE_ARRAY);
$userinfo = fetch_userinfo($this->vbulletin->userinfo['userid']);
$userdm->set_existing($userinfo);
if (!$this->vbulletin->userinfo["$fcust"] and !$this->vbulletin->userinfo["$fpass"])
{
$rand = rand($this->vbulletin->options['memarea_numstart'], $this->vbulletin->
options['memarea_numend']);
$num = $this->vbulletin->options['custnum_prefix'] . substr(md5($rand), 0, $this->
vbulletin->options['memarea_custnumleng'] - strlen($this->vbulletin->options['custnum_prefix']));
$userdm->set($fcust, $num);
$pass = substr(md5(time() . $num . $rand . rand(0, 2000)), 0, $this->vbulletin->
options['memarea_custnumleng']);
$userdm->set($fpass, $pass);
$this->sendCustomerInfo($this->vbulletin->userinfo['userid'], $this->vbulletin->
userinfo['username'], $this->vbulletin->userinfo['email'], $num, $pass);
}
if ($usergroup or $usergroup !== '' or $usergroup !== '0')
{
if ($usergroup != $this->vbulletin->userinfo['usergroupid'])
{
$ma_info['oldgroup'] = $this->vbulletin->userinfo['usergroupid'];
$userdm->set('usergroupid', $usergroup);
}
}
if ($ma_info)
{
$ma_info = serialize($ma_info);
$userdm->set($finfo, $ma_info);
}
$userdm->pre_save();
if (count($userdm->errors) == 0)
{
$userdm->save();
return true;
}
else
{
var_dump($userdm->errors);
return false;
}
}

update query not updating table in transactions

I m trying to get and update data at same time but after getting data transaction is rolled back, because table is not updating.
Controller -
public function addAmount()
{
$this->form_validation->set_rules('balance_id', 'Balance Id', 'required|trim');
$this->form_validation->set_rules('farmer_id', 'farmer_id', 'required|trim');
$this->form_validation->set_rules('amount', 'amount', 'required|trim');
$this->form_validation->set_rules('amount_discount', 'discount', 'required|trim');
$this->form_validation->set_rules('payment_mode', 'payment mode', 'required|trim');
if ($this->form_validation->run() == false) {
$data = array(
'amount' => form_error('amount'),
'balance_id' => form_error('balance_id'),
'farmer_id' => form_error('farmer_id'),
'amount_discount' => form_error('amount_discount'),
'payment_mode' => form_error('payment_mode'),
);
$array = array('status' => 'fail', 'error' => $data);
echo json_encode($array);
} else {
$id =$this->generate_otp();
$data = array(
'farmer_id' => $this->input->post('farmer_id'),
'balance_id' => $this->input->post('balance_id'),
'amount_paid' => $this->input->post('amount'),
'paying_date' => $this->input->post('date'),
'amount_discount' => $this->input->post('amount_discount'),
'description' => $this->input->post('description'),
'payment_mode' => $this->input->post('payment_mode'),
'payment_id' =>$id,
);
$inserted_id = $this->advance_model->amount_deposit($data);
echo '<pre>'; print_r($inserted_id); echo ("</pre>"); exit();
$array = array('status' => 'success', 'error' => '');
echo json_encode($array);
}
}
Model:
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
return $query->row();
if(!empty($query)){
$b =$query['balance'];
$balance =$b - $paid_amount;
}
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}
When amount to be added the balance amount need to be update automatically, but now transaction is roll back because not able to update balance amount after getting it from same table, thanks in advance.
Just added foreach loop and removed return statement now it's working fine.
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
$result = $query->result();
}
if (!empty($result) && isset($result)) {
foreach ($result as $key => $balance_value) {
$balance_id = $balance_value->balance_id;
$balanceAmount = $balance_value->balance;
$balance = $balanceAmount - $paid_amount;
}
$this->db->where('balance_id', $balance_id);
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}

Parsing returns an empty value

I make a parser of items from DotA 2 user inventory in the Steam service. Every time I try to parse user data, I get an empty value:
{"success":true,"items":[]}, but there are items in my Steam inventory.
My function to parse items:
public function loadMyInventory() {
if(Auth::guest()) return ['success' => false];
$prices = json_decode(Storage::get('prices.txt'), true);
$response = json_decode(file_get_contents('https://steamcommunity.com/inventory/'.$this->user->steamid64.'/570/2?l=russian&count=5000'), true);
if(time() < (Session::get('InvUPD') + 5)) {
return [
'success' => false,
'msg' => 'Error, repeat in '.(Session::get('InvUPD') - time() + 5).' сек.',
'status' => 'error'
];
}
//return $response;
$inventory = [];
foreach($response['assets'] as $item) {
$find = 0;
foreach($response['descriptions'] as $descriptions) {
if($find == 0) {
if(($descriptions['classid'] == $item['classid']) && ($descriptions['instanceid'] == $item['instanceid'])) {
$find++;
# If we find the price of an item, then move on.
if(isset($prices[$descriptions['market_hash_name']])) {
# Search data
$price = $prices[$descriptions['market_hash_name']]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($descriptions['tradable'] == 0) || ($descriptions['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
# Adding to Array
$inventory[] = [
'name' => $descriptions['market_name'],
'price' => floor($price),
'color' => $this->getRarity($descriptions['tags']),
'tradable' => $descriptions['tradable'],
'class' => $class,
'text' => $text,
'classid' => $item['classid'],
'assetid' => $item['assetid'],
'instanceid' => $item['instanceid']
];
}
}
}
}
}
Session::put('InvUPD', (time() + 5));
return [
'success' => true,
'items' => $inventory
];
}
But should return approximately the following value:
{"success":true,"items":[{"classid":"2274725521","instanceid":"57949762","assetid":"18235196074","market_hash_name":"Full-Bore Bonanza","price":26}]}
Where my mistake?
First of all, you are iterating on descriptions for every assets, which is assets*descriptions iteration, it's quite a lot, but you can optimize this.
let's loop once for descriptions and assign classid and instanceid as object key.
$assets = $response["assets"];
$descriptions = $response["descriptions"];
$newDescriptions=[];
foreach($descriptions as $d){
$newDescriptions[$d["classid"]][$d["instanceid"]] = $d;
}
this will give as the ability to not loop over description each time, we can access the description of certain asset directly $newDescriptions[$classid][$instanceid]]
foreach($assets as $a){
if(isset($newDescriptions[$a["classid"]]) && isset($newDescriptions[$a["classid"]][$a["instanceid"]])){
$assetDescription = $newDescriptions[$a["classid"]][$a["instanceid"]];
$inventory = [];
if(isset($prices[$assetDescription["market_hash_name"]])){
$price = $prices[$assetDescription['market_hash_name']]["price"]*$this->config->curs;
$class = false;
$text = false;
if($price <= $this->config->min_dep_sum) {
$price = 0;
$text = 'Cheap';
$class = 'minPrice';
}
if(($assetDescription['tradable'] == 0) || ($assetDescription['marketable'] == 0)) {
$price = 0;
$class = 'minPrice';
$text = 'Not tradable';
}
$inventory["priceFound"][] = [
'name' => $assetDescription['market_name'],
'price' => floor($price),
'color' => $this->getRarity($assetDescription['tags']),
'tradable' => $assetDescription['tradable'],
'class' => $class,
'text' => $text,
'classid' => $a['classid'],
'assetid' => $a['assetid'],
'instanceid' => $a['instanceid']
];
}else{
$inventory["priceNotFound"][] = $assetDescription["market_hash_name"];
}
}
}
About your mistake:
are you Sure your "prices.txt" contains market_hash_name?
I don't see any other issue yet, operationg on the data you have provided in comment, I got print of variable $assetDescription. Please doublecheck variable $prices.

zend multicheckboxes form controller

Merged with multicheckboxes zend form multi populate.
i did do the form with multicheckboxs and it works fine when insert or update but the my problem is how to populate all the multi boxes that is checked form the database this is the code but it doesn't show just one checkbox is checked
$id = (int) $this->_request->getParam('id');
//The incoming request
$request = $this->getRequest();
//initialize form
$form = new Admin_Form_DownFooterTab();
//instance of db
$db = Zend_Db_Table::getDefaultAdapter();
if ($this->getRequest()->isPost()) {
if ($form->isValid($request->getPost())) {
if (isset($id) && $id != "") {
$gettag = $form->getValue('tag_id');
$gettags = count($gettag);
try {
//shift the orders to
$select = $db->select()->from(array('t' => 'tab'), array('t.id',
't.title',
't.tab_position',
't.order',
't.is_active',
't.is_deleted'))->where('id = ?', $id);
$currentTab = $db->fetchRow($select);
$var3 = array('tab.order' => new Zend_Db_Expr('tab.order - 1'));
$var4 = array('tab.order >= ' . $currentTab['order'], 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var3, $var4);
$var = array('tab.order' => new Zend_Db_Expr('tab.order + 1'));
$var2 = array('tab.order >= ' . $form->getValue('order'), 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var, $var2);
$db->delete('tab_tag', array('tab_id = ?' => $id));
foreach ($gettag as $value) {
$db->insert('tab_tag',
array(
'tag_id' => $value,
'tab_id' => $id
));
}
$db->update('tab', array(
'title' => $form->getValue('title'),
'body' => $form->getValue('body'),
'is_active' => $form->getValue('is_active'),
'banner_link' => $form->getValue('banner_link'),
'tab_path' => $form->getValue('tab_path'),
'link_open' => $form->getValue('link_open'),
'tab_position' => $form->getValue('tab_position'),
'tab_parent' => $form->getValue('tab_parent')
),
array('id =?' => $id));
$this->flash('Tab Updated', 'admin/tab');
} catch (Exception $e) {
$this->flash($e->getMessage(), 'admin/tab');
}
} else {
try {
$formValues = $form->getValues();
$formValues['created_by'] = 1;
$formValues['created_date'] = date('Y/m/d H:i:s');
$formValues['is_deleted'] = 0;
$var = array('tab.order' => new Zend_Db_Expr('tab.order + 1'));
$var2 = array('tab.order >= ' . $form->getValue('order'), 'is_active=1', 'is_deleted=0', 'tab_position=4');
$db->update('tab', $var, $var2);
foreach ($gettag as $value) {
$db->insert('tab_tag',
array(
'tag_id' => $value,
'tab_id' => $id
));
}
$db->insert('tab', array(
'title' => $form->getValue('title'),
'body' => $form->getValue('body'),
'is_active' => $form->getValue('is_active'),
'banner_link' => $form->getValue('banner_link'),
'tab_path' => $form->getValue('tab_path'),
'link_open' => $form->getValue('link_open'),
'tab_position' => $form->getValue('tab_position'),
'tab_parent' => $form->getValue('tab_parent')
));
$this->flash('Tab inserted', 'admin/tab');
} catch (Exception $e) {
$this->flash($e->getMessage(), 'admin/tab');
}
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
if (isset($id) && $id != "") {
$values = $db->fetchRow("SELECT * FROM tab WHERE id = ?", $id);
$form->populate($values);
}
$this->view->form = $form;
}
$ddlCat_parent->setMultiOptions($cats);
$this->view->form = $form;
}

Categories