How to update or insert new data on codeigniter - php

I'm setting up a rest-API on my server, and I want to update a table (i.e "comp_holding_stock"). but every time I test to post new data it returns "No item found"
Here is my controller
public function create_comp_holding_stock(){
$returnArr['status'] = '0';
$returnArr['response'] = '';
try {
if (!$this->input->post()) {
$returnArr['response'] = "Only POST method is allowed";
} else {
$holding_stock_data = array(
'comp_id' => $this->input->post('comp_id'),
'customer_id' => $this->input->post('customer_id'),
'quantity' => $this->input->post('quantity'),
'date' => date('Y-m-d H:i:s')
);
if (!isset($holding_stock_data)) {
$returnArr['response'] = "Some Parameters are missing";
} else {
$customer = $this->Customer->save_holding_stock($holding_stock_data);
if (!$customer) {
$returnArr['response'] = 'No items found';
} else {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
}
}
}
} catch (Exception $ex) {
$returnArr['response'] = "Error in connection";
$returnArr['error'] = $ex->getMessage();
}
$response = json_encode($returnArr, JSON_PRETTY_PRINT);
echo $response;
}
And here is my model below
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$success = $this->db->insert('comp_holding_stock', $holding_stock_data);
return $success;;
}
what am i doing wrong? what is the best approach to this scenarios

I would recommend try to check if you have load model in your controller.
And in your model try to do this.
public function save_holding_stock($holding_stock_data, $comp_id=FALSE)
{
if(!$comp_id == -1 || !$this->exists($comp_id))
{
if($this->db->insert('comp_holding_stock', $holding_stock_data))
{
$holding_stock_data['comp_id'] = $this->db->insert_id();
return TRUE;
}
return FALSE;
}
$this->db->where('comp_id', $comp_id);
return $this->db->update('comp_holding_stock', $holding_stock_data);
}

Try these changes in your code
In your controller,
$customer = $this->Customer->save_holding_stock($holding_stock_data);
$save_status = $this->db->affected_rows();
if ($save_status>0) {
$returnArr['status'] = '1';
$returnArr['response'] = $customer;
} else {
$returnArr['response'] = 'No items found';
}
In your model,
public function save_holding_stock($holding_stock_data)
{
// $this->db->trans_start();
$this->db->insert('comp_holding_stock', $holding_stock_data);
}

Related

php redis insert a data at a same time with few queues error

There are 3 queues in redis.
If I insert a data at a same time with different browsers, both requests are accepted.
I get 2 duplicated records. Any helps?
For example, the first request is on the 1st queue.
At the second request, 2nd queue is searched for finding the data.
But the data doesn't exist in the queue.
The second request is inserted on the queue.
Is it understandable?
public function save($evt_no, $type = "redis") {
$name = '';
$res = true;
try{
$headers = getallheaders();
$bodys = $_REQUEST;
$session = $_SESSION;
foreach ($_FILES as $fileKey=>$fileVal) {
if ($fileVal['error'] == 0) {
try {
$uploaded_row = $this->fileL->upload('queueEventParticipant', $fileKey, array() ,'queue');
} catch (\Exception $ex) {
throw $ex;
}
$bodys['file'][_return_numeric($fileKey)] = $uploaded_row;
}
}
$data = array(
'header' => $headers,
'body' => $bodys,
'session' => $session
);
$data['body']['evt_no'] = $evt_no;
$data = json_encode($data);
if($type == "redis"){
$name = $this->attendQueueRedisService->setNewRsvp($data);
} else {
throw new \Exception("No exist");
}
} catch (\Exception $ex){
log_message("error", $ex->getMessage());
throw $ex;
}
if($res){
return $name;
} else {
return "Error";
}
}
class AttendQueueRedisService extends CI_Model {
private $redisClient;
private $redisConfig;
const PREFIX_DONE = 'done_';
const PREFIX_ERROR = 'error_';
public function __construct() {
parent::__construct();
if ($this->load->config('redis', true, true)) {
$this->redisConfig = $this->config->config['redis'];
}
$this->redisClient = new Redis();
$this->redisClient->connect($this->redisConfig['hostname'], $this->redisConfig['port']);
$this->redisClient->auth($this->redisConfig['auth']);
$this->redisClient->select($this->redisConfig['queue']);
}
public function setNewRsvp($data) {
$key = uniqid('rsvp_'.gethostname().'_',true).':redis';
$this->redisClient->set($key, $data, 60 * 30);
return $key;
}
}

Yii No data received in post method only on server

Created an API endpoint I which I am submitted data as the body in postman, but it is always empty on the server whereas it works fine on localhost.
Please look at the request
The same request works on localhost but not online. Here is code on the server side I am using Yii::$app->request->post() to dump the data, here is the full code of that endpoint. I had tried $_POST,$_REQUEST every request is empty on the server,
public function actionSocialcheck()
{
$data = [];
$model = new User();
var_dump(Yii::$app->request->post());
if ($model->load(Yii::$app->request->post(),'')) {
$social = User::findBySocialLogin($model->socialLogin);
if (empty($social)) {
$data['status'] = self::API_OK;
$data['check'] = false;
} else {
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
// $usercl=new User();
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
} else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}
When I try the same request on the local server it works fine here is the output of that
Can you please help me out in this case. Thanks
public function actionSocialcheck(){
if(Yii::$app->request->isPost){
$data = [];
$social = User::findBySocialLogin(Yii::$app->request->post('socialLogin'));
if (empty($social)){
$data['status'] = self::API_OK;
$data['check'] = false;
}else{
if (Yii::$app->request->post('role_id') != $social->role_id) {
$data['error'] = \Yii::t('app', "You don't have permission to login as " . User::getRoleOptions($social->role_id));
return $this->response = $data;
}
$data['error'] = \yii::t('app', "Social ID already exists.");
$data['check'] = true;
$data['status'] = self::API_OK;
$data['detail'] =$social;
$data['access-token'] = $social->access_token;
$loginarr = array(
'device_name' => Yii::$app->request->post('device_name'),
'device_token' => Yii::$app->request->post('device_token'),
'device_type' => Yii::$app->request->post('device_type'),
);
$data['login_detail']=$loginarr;
}
}else {
$data['error'] = "Data not posted.";
}
$this->response = $data;
}

How to get a value of particular column from the object variable in laravel

From the model TagModel i can filter the value which i want it, but value is stored in the form of object variable. To play with those data in controller i am not able to pluck the particular id.
This is my model
public static function getLatestTag($name){
return $tagIds =DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->get();
}
This is my controller code:
foreach ($newTags as $newTag) {
$productTagIds[] = TagModel::getLatestTag($newTag);
dd($id);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($productTagIds as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
the value which i want is stored in the variable $productTagIds which is object variable. How can I pluck just id from this?
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
$productTagIds[]=$objectTagProduct->id;
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
The code might flash a certain error that have to troubleshoot by yourself. I have kept
$productTagIds[]=$objectTagProduct->id;
after $objectTagProduct->save(); please try it
public static function getLatestTag($name){
return $tagIds = DB::table('tags')
->where ('is_deleted',0)
->where('name',$name)
->pluck(id);
}
public static function getLatestTag($name){
return App\TagModel::where('is_deleted',0)->where('name',$name)->first()->id;
}
$ids = [];
foreach ($newTags as $newTag) {
$productTagId = TagModel::getLatestTag($newTag);
array_push($ids,$productTagId);
}
$productId = (int)ProductManagementModel::getMaxId();
foreach ($ids as $productTagId) {
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTag->save();
}
try to use eloquent like this
to get the particular value from the object class variable
$productTagIds[]=$objectTagProduct->id;`
public function addProduct()
{
foreach(Input::get('tagName') as $checkTag){
$newTags[]=$checkTag;
}
foreach ($newTags as $newTag) {
if(TagModel::checkExist($newTag)){
$tagExist[] = TagModel::checkExist($newTag);
$message = 'The tag <b>'.$checkTag.'</b> already exist';
Session::flash('class', 'alert alert-error');
Session::flash('message', $message);
return View::make('admin.product_management.add');
}
else {
$objectTagProduct = new TagModel;
$objectTagProduct ->name = $newTag;
$objectTagProduct->save();
}
}
$objectProduct = new ProductManagementModel;
$objectProduct->product_name = Input::get('product_name');
$objectProduct->product_url = $productUrl;
$objectProduct->category_id = Input::get('category_id');
$objectProduct->product_cost = Input::get('product_cost');
$objectProduct->product_short_description = Input::get('product_short_description');
$objectProduct->product_description = Input::get('product_description');
$objectProduct->is_active = Input::get('is_active');
$objectProduct->created_at = Auth::user()->id;
$objectProduct->updated_at = Auth::user()->id;
if($logo != '')
{
$objectProduct->product_attachment = $logo;
}
$objectProduct->save();
$productId = (int)ProductManagementModel::getMaxId();
//dd($productId);
foreach ($productTagIds as $productTagId) {
//dd($productTagIds);
$productTag = new ProductTagModel;
$productTag ->product_id = $productId;
$productTag ->tag_id = $productTagId;
$productTagIds[]=$objectTagProduct->id;
$productTag->save();
}
if($objectProduct->id) {
Session::flash('class', 'alert alert-success');
Session::flash('message', 'Product successfully added');
return View::make('admin.product_management.add');
} else {
Session::flash('class', 'alert alert-error');
Session::flash('message', 'Something error');
return View::make('admin.product_management.add');
}
}
I came to knew that to get the data from object class variable $productTagIds[]=$objectTagProduct->id;
But i am confused with its flow and where to execute this code.

Array to string conversion Error in Laravel 4.2

I was working in one Laravel Project using 92Five App. when access user List. its goto Something Went Wrong Page. Its Display Array to string conversion Error in Error Log.
In User Controller Following Functions are Defined.
Error :
[2016-08-09 13:13:12] log.ERROR: Something Went Wrong in User
Repository - getAllUsersData():Array to string conversion [] []
My Code :
public function getAllUsersData()
{
try{
$users = array();
$tempUsers = \User::all()->toArray();
$users = $this->getGroupBaseRole($tempUsers);
return $users;
}
catch (\Exception $e)
{
\Log::error('Something Went Wrong in User Repository - getAllUsersData():'. $e->getMessage());
throw new SomeThingWentWrongException();
}
}
public function getGroupBaseRole($groupMembersInfo) {
$data = [];
if(!empty($groupMembersInfo) && isset($groupMembersInfo)) {
foreach($groupMembersInfo as $user)
{
$banned = false;
$suspended = false;
$loginAttempt = 0;
$usersThrottle = \Throttle::where('user_id',$user['id'])->get()->toArray();
// print_r($usersThrottle); exit;
if(sizeof($usersThrottle) != 0)
{
foreach($usersThrottle as $userThrottle)
{
if($userThrottle['banned'] == true)
{
$banned = true;
}
if($userThrottle['suspended'] == true)
{
$suspended = true;
}
$loginAttempt = $loginAttempt + $userThrottle['attempts'];
}
$user['banned'] = $banned;
$user['suspended'] = $suspended;
$user['loginAttempt'] = $loginAttempt;
}
else
{
$user['banned'] = false;
$user['suspended'] = false;
$user['loginAttempt'] = 0;
}
$groupUser = \Sentry::findUserById($user['id']);
$groups = $groupUser->getGroups()->toArray();
if(sizeof($groups)!=0)
{
$user['role'] =$groups[0]['name'];
}
else
{
$user['role'] = '';
}
$data[] = $user;
}
}
return $data;
}
It seeems getGroupBaseRole() method accepts string, but you're trying to pass an array $tempUsers as first argument.

Magento Get Category URL in Index Controller

I am having troubles getting my redirectURL to grab the current URL inside of my IndexController. I have written something very similar that grabs the current product URL, but this is for the category. Can someone explain what I may have done wrong?
<?php
class Magestore_Categoryinquiry_IndexController extends Mage_Core_Controller_Front_Action
{
public function indexAction()
{
$this->_initLayoutMessages('catalog/session');
$this->loadLayout();
$this->renderLayout();
}
public function submitAction() {
$data = $this->getRequest()->getPost();
$error = false;
if($data) {
$category = Mage::getModel('catalog/category')->load($data['category_id']);
try {
$postObject = new Varien_Object();
$postObject->setData($data);
$error = false;
if (Mage::helper('categoryinquiry')->isRequireFname()) {
if (!Zend_Validate::is(trim($data['fname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireLname()) {
if (!Zend_Validate::is(trim($data['lname']) , 'NotEmpty')) {
$error = true;
}
}
if (Mage::helper('categoryinquiry')->isRequireEmail()) {
if (!Zend_Validate::is(trim($data['customer_email']), 'EmailAddress')) {
$error = true;
}
}
if (Zend_Validate::is(trim($data['hideit']), 'NotEmpty')) {
$error = true;
}
if ($error) {
throw new Exception();
}
$model = Mage::getModel('categoryinquiry/categoryinquiry');
$data['store_id'] = Mage::app()->getStore()->getId();
$data['status'] = 1;
$data['created_time'] = now();
$data['updated_time'] = now();
$data['category_name'] = $category->getName();
$categoryinquiry = $this->getLayout()->createBlock('categoryinquiry/sendtocustomer')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtocustomer.phtml')
->toHtml();
$customercontact = $this->getLayout()->createBlock('categoryinquiry/sendtoadmin')
->setInformation($data)
->setTemplate('categoryinquiry/email/sendtoadmin.phtml')
->toHtml();
$model->setData($data)->save()
->sendMailToCustomer($model, $categoryinquiry)
->sendMailToAdmin($model, $customercontact)
;
Mage::getSingleton('catalog/session')->addSuccess(Mage::helper('categoryinquiry')->getSuccessMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
} catch (Exception $e) {
Mage::getSingleton('catalog/session')->addError(Mage::helper('categoryinquiry')->getErrorMessage());
$this->_redirectUrl($category->getCategoryUrl());
return;
}
}
}
}

Categories