Laravel insert data twice when timeout occurs - php

I noticed laravel re-preform the insertion action when the timeout occurs
How can I shop it from retiring to insert the data again when timeout error fires ?
loop
foreach ($comments_data as $comment_data)
{
if ( ! empty($comment_data['date']))
{
$total_rating[] = $this->check_rating_value($comment_data['rating']);
$comment_id = ( new Comment() )->saveComments($shop, $comment_data, $product_id, $urls, $shop_options);
( new Comments_images() )->save_images($comment_id, $shop, $comment_data['images']);
}
}
inserting code
public function saveComments($shop, $comments_data, $product_id, $url, $shop_options)
{
$date = Carbon::parse($comments_data['date']);
if ($shop_options->filter_status == 1)
{
$comments = str_replace(explode(',', $shop_options->filter_find_words), explode(',', $shop_options->filter_alter_words), $comments_data['comment']);
} else
{
$comments = $comments_data['comment'];
}
$faker = Factory::create();
$this->shop_name = $shop;
$this->comment = $comments;
$this->rating = $this->check_rating_value($comments_data['rating']);
$this->product_id = $product_id;
$this->user_name = $faker->userName;
$this->product_url = $url;
$this->created_at = $date->toDateTimeString();
$this->country = $comments_data['country'] == 'IL' ? 'PS' : $comments_data['country'];
$this->view = 1;
$this->save();
return $this->id;
}

Related

Error: Cannot use object of type Symfony\Component\HttpFoundation\Request as array

When I showed it in a browser when upgrading to symfony3, I had a title error (line 25).
I had questions on similar mistakes in StackOverflow, but I think it's a different trend.
I want to know how it can be improved.
Stack Trace
[1] Symfony\Component\Debug\Exception\FatalErrorException: Error:
Cannot use object of type Symfony\Component\HttpFoundation\Request as array
at n/a
in /Symfony/.../Bundle/Listener/PortalListener.php line 25
Code
PortalListener.php
<?php
namespace Ahi\Sp\PublicBundle\Listener;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Ahi\Sp\PublicBundle\Controller\BaseController;
use Ahi\Sp\PublicBundle\Model\Service\AhiCookieService;
use Symfony\Component\HttpFoundation\Request;
/**
*/
class PortalListener
{
/*
*
* #param FilterControllerEvent $event
*/
public function preControllerExecute(FilterControllerEvent $event, Request $request)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$_controller = $event->getRequest();
if (isset($_controller[0])) { //line25
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}
BaseController.php
<?php
namespace Ahi\Sp\PublicBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\HttpException;
/ **
* Front controller.
* /
abstract class BaseController extends Controller
{
const MAX_ITEM_COUNT = 4; // Maximum number to get the item part number from the coordination. (You can get up to 4)
protected $parameters = array();
protected $response = null;
protected $cookie = null;
public function preExecute (Request $request) {
$this->cookie = $this->get('public.ahiCookieService');
// ---------------------------------------
// Gender (The order is the member's gender → portal top gender button → brand → shop → MEN'S $LADIE'S button)
$this->gender = $this->cookie->get('gender');
// Get the brand and overwrite the gender of the brand
$this->brand = null;
$brandDir = null;
$brandDirUrlParam = $request->attributes->get('brandDir');
$brandDirGetParam = $request->query->get('brandDir');
if ($brandDirUrlParam) {
$brandDir = $brandDirUrlParam;
} elseif ($brandDirGetParam) {
$brandDir = $brandDirGetParam;
}
$brandService = $this->get('public.brandService');
if ($brandDir) {
$brand = $brandService->getBrand($brandDir);
if (!$brand) {
throw $this->createBrandNotFoundException();
}
if(!$this->isPreview() && !$brand->getDispFlg()) {
throw $this->createBrandNotFoundException();
}
$brandSex = $brand->getBrandSex();
if ($brandSex != 2) {
$this->gender = $brandSex;
}
$this->brand = $brand;
}
// shop --------------------------------->
$this->shop = null;
$shopDir = null;
$shopDirUrlParam = $request->attributes->get('shopDir');
$shopDirGetParam = $request->query->get('shopDir');
if ($shopDirUrlParam) {
$shopDir = $shopDirUrlParam;
} elseif ($shopDirGetParam) {
$shopDir = $shopDirGetParam;
}
$this->shopDir = $shopDir;
$shopService = $this->get('public.shopService');
if ($shopDir) {
$shop = $shopService->getShop($shopDir);
if (!$shop) {
throw $this->createShopNotFoundException();
}
if (!$this->isPreview() && !$shop->getDispFlg()) {
if ($shop->getRedirectFlg() == true) {
$redirectUrl = $shop->getRedirectUrl();
if (empty($redirectUrl)) {
$redirectUrl = $this->generateUrl('ahi_sp_public_brand_top', array('brandDir' => $shop->getBrand()->getDirName()));
}
throw new ShopRedirectException($redirectUrl);
} else {
throw $this->createShopNotFoundException();
}
}
$shopSex = $shop->getShopSex();
if ($shopSex != 2) {
$this->gender = $shopSex;
}
$this->shop = $shop;
}
// shop <---------------------------------
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
if ($this->getRequest()->get('_route') !== 'ahi_sp_public_portal_top') {
$gender = $request->query->get('gender');
if ($gender !== null) {
$this->gender = $gender;
}
}
if ($this->gender !== null) {
$this->gender = intval($this->gender);
$this->cookie->set('gender', $this->gender, 30);
$this->cookie->set('ec_gender', $this->gender, 30);
}
if ($this->gender === 0 or $this->gender === 1) {
$this->paramsSex = array('sex'=> array($this->gender, 2));
} else {
$this->paramsSex = array('sex'=> array(0, 1, 2));
}
$mid = $this->cookie->get('member_id');
$session = $request->getSession();
if ($mid && !$session->has('favoriteShops')) {
$route = $this->container->getParameter('ats_http');
$list = $this->container->getParameter('favorite_shop_list');
$url = $route . $list . $mid;
$ahiStoreIdList = file_get_contents($url);
$favoriteShops = array();
if ($ahiStoreIdList !=='') {
$ahiStoreIdArray = explode(",", $ahiStoreIdList);
$shopService = $this->get("public.shopService");
$sortKey = array();
foreach ($ahiStoreIdArray as $key => $storeId) {
$id = explode(':', $storeId);
$shop = $shopService->getShopById($id[1]);
if ($shop) {
$favoriteShops[$key]['shopName'] = $shop->getShopName();
$favoriteShops[$key]['shopDir'] = $shop->getDirName();
$sortKey[$key] = $shop->getShopName();
}
}
array_multisort($sortKey, SORT_ASC, $favoriteShops);
}
$session->set('favoriteShops', $favoriteShops);
}
$trend_tag_list_limit = $this->container->getParameter("trend_tag_list_limit");
if(!$brandDirUrlParam and !$shopDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand();
$this->parameters['prefBrands'] = $this->service('coordinate')->getBrandPerPref();
$this->parameters['shopBrandPrefectures'] = $this->service('brand')->getPrefExistBrand();
$this->parameters['shopPrefBrands'] = $this->service('brand')->getBrandPerPref();
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->paramsSex,false,$trend_tag_list_limit);
}elseif($brandDirUrlParam){
$this->parameters['brandPrefectures'] = $this->service('coordinate')->getPrefExistBrand($brandDirUrlParam);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->brand,false,$trend_tag_list_limit);
}else{
$this->parameters['coordinateCount'] = $this->service('coordinate')->getCountArticle(
$this->brand,
$this->shop
);
$this->parameters['trendTags'] = $this->service('ecTrendTag','common')->getTrendTag($this->shop->getBrand(),false,$trend_tag_list_limit);
}
}
Version
Cent OS 6.7
PHP 5.6
Symfony3.0.9
The error was resolved when I fixed it as follows.
public function preControllerExecute(FilterControllerEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$request = $event->getRequest();
$_controller = $event->getController();
if (isset($_controller[0])) {
$controller = $_controller[0];
if (method_exists($controller, 'preExecute')) {
$controller->preExecute($request);
}
}
}
}

Laravel - Select box

I have the following select box which lists the all users. I need list users only which groupID is==3 How can I do that ?
Thanks in advance
<div class="form-group " >
<label for="Staff" class=" control-label col-md-4 text-left"> Staff </label>
<div class="col-md-7">
<select name='Staff' rows='5' id='Staff' class='select2 ' ></select>
</div>
<div class="col-md-1">
</div>
</div>
Controller
use App\Http\Controllers\controller; use App\Models\Adminorders; use Illuminate\Http\Request; use Illuminate\Pagination\LengthAwarePaginator as Paginator; use Validator, Input, Redirect ;
class AdminordersController extends Controller {
protected $layout = "layouts.main";
protected $data = array();
public $module = 'adminorders';
static $per_page = '10';
public function __construct()
{
parent::__construct();
$this->beforeFilter('csrf', array('on'=>'post'));
$this->model = new Adminorders();
$this->modelview = new \App\Models\Orderdetail();
$this->info = $this->model->makeInfo( $this->module);
$this->access = $this->model->validAccess($this->info['id']);
$this->data = array(
'pageTitle' => $this->info['title'],
'pageNote' => $this->info['note'],
'pageModule'=> 'adminorders',
'return' => self::returnUrl()
);
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'][0] : array());
}
public function getIndex( Request $request )
{
if($this->access['is_view'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$sort = (!is_null($request->input('sort')) ? $request->input('sort') : 'SiparisID');
$order = (!is_null($request->input('order')) ? $request->input('order') : 'asc');
// End Filter sort and order for query
// Filter Search for query
$filter = '';
if(!is_null($request->input('search')))
{
$search = $this->buildSearch('maps');
$filter = $search['param'];
$this->data['search_map'] = $search['maps'];
}
$page = $request->input('page', 1);
$params = array(
'page' => $page ,
'limit' => (!is_null($request->input('rows')) ? filter_var($request->input('rows'),FILTER_VALIDATE_INT) : static::$per_page ) ,
'sort' => $sort ,
'order' => $order,
'params' => $filter,
'global' => (isset($this->access['is_global']) ? $this->access['is_global'] : 0 )
);
// Get Query
$results = $this->model->getRows( $params );
// Build pagination setting
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($results['rows'], $results['total'], $params['limit']);
$pagination->setPath('adminorders');
$this->data['rowData'] = $results['rows'];
// Build Pagination
$this->data['pagination'] = $pagination;
// Build pager number and append current param GET
$this->data['pager'] = $this->injectPaginate();
// Row grid Number
$this->data['i'] = ($page * $params['limit'])- $params['limit'];
// Grid Configuration
$this->data['tableGrid'] = $this->info['config']['grid'];
$this->data['tableForm'] = $this->info['config']['forms'];
// Group users permission
$this->data['access'] = $this->access;
// Detail from master if any
// Master detail link if any
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
// Render into template
return view('adminorders.index',$this->data);
}
function getUpdate(Request $request, $id = null)
{
if($id =='')
{
if($this->access['is_add'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
if($id !='')
{
if($this->access['is_edit'] ==0 )
return Redirect::to('dashboard')->with('messagetext',\Lang::get('core.note_restric'))->with('msgstatus','error');
}
$row = $this->model->find($id);
if($row)
{
$this->data['row'] = $row;
} else {
$this->data['row'] = $this->model->getColumnTable('tb_orders');
}
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['forms']);
$relation_key = $this->modelview->makeInfo($this->info['config']['subform']['module']);
$this->data['accesschild'] = $this->modelview->validAccess($relation_key['id']);
$this->data['relation_key'] = $relation_key['key'];
$this->data['subform'] = $this->detailview($this->modelview , $this->info['config']['subform'] ,$id );
$this->data['id'] = $id;
return view('adminorders.form',$this->data);
}
public function getShow( Request $request, $id = null)
{
if($this->access['is_detail'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
$row = $this->model->getRow($id);
if($row)
{
$this->data['row'] = $row;
$this->data['fields'] = \SiteHelpers::fieldLang($this->info['config']['grid']);
$this->data['id'] = $id;
$this->data['access'] = $this->access;
$this->data['subgrid'] = (isset($this->info['config']['subgrid']) ? $this->info['config']['subgrid'] : array());
$this->data['prevnext'] = $this->model->prevNext($id);
return view('adminorders.view',$this->data);
} else {
return Redirect::to('adminorders')->with('messagetext','Record Not Found !')->with('msgstatus','error');
}
}
function postSave( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_adminorders');
$id = $this->model->insertRow($data , $request->input('SiparisID'));
$this->detailviewsave( $this->modelview , $request->all() ,$this->info['config']['subform'] , $id) ;
if(!is_null($request->input('apply')))
{
$return = 'adminorders/update/'.$id.'?return='.self::returnUrl();
} else {
$return = 'adminorders?return='.self::returnUrl();
}
// Insert logs into database
if($request->input('SiparisID') =='')
{
\SiteHelpers::auditTrail( $request , 'New Data with ID '.$id.' Has been Inserted !');
} else {
\SiteHelpers::auditTrail($request ,'Data with ID '.$id.' Has been Updated !');
}
return Redirect::to($return)->with('messagetext',\Lang::get('core.note_success'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders/update/'.$request->input('SiparisID'))->with('messagetext',\Lang::get('core.note_error'))->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
public function postDelete( Request $request)
{
if($this->access['is_remove'] ==0)
return Redirect::to('dashboard')
->with('messagetext', \Lang::get('core.note_restric'))->with('msgstatus','error');
// delete multipe rows
if(count($request->input('ids')) >=1)
{
$this->model->destroy($request->input('ids'));
\DB::table('tb_orderdetail')->whereIn('SiparisID',$request->input('ids'))->delete();
\SiteHelpers::auditTrail( $request , "ID : ".implode(",",$request->input('ids'))." , Has Been Removed Successfull");
// redirect
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext', \Lang::get('core.note_success_delete'))->with('msgstatus','success');
} else {
return Redirect::to('adminorders?return='.self::returnUrl())
->with('messagetext','No Item Deleted')->with('msgstatus','error');
}
}
public static function display( )
{
$mode = isset($_GET['view']) ? 'view' : 'default' ;
$model = new Adminorders();
$info = $model::makeInfo('adminorders');
$data = array(
'pageTitle' => $info['title'],
'pageNote' => $info['note']
);
if($mode == 'view')
{
$id = $_GET['view'];
$row = $model::getRow($id);
if($row)
{
$data['row'] = $row;
$data['fields'] = \SiteHelpers::fieldLang($info['config']['grid']);
$data['id'] = $id;
return view('adminorders.public.view',$data);
}
} else {
$page = isset($_GET['page']) ? $_GET['page'] : 1;
$params = array(
'page' => $page ,
'limit' => (isset($_GET['rows']) ? filter_var($_GET['rows'],FILTER_VALIDATE_INT) : 10 ) ,
'sort' => 'SiparisID' ,
'order' => 'asc',
'params' => '',
'global' => 1
);
$result = $model::getRows( $params );
$data['tableGrid'] = $info['config']['grid'];
$data['rowData'] = $result['rows'];
$page = $page >= 1 && filter_var($page, FILTER_VALIDATE_INT) !== false ? $page : 1;
$pagination = new Paginator($result['rows'], $result['total'], $params['limit']);
$pagination->setPath('');
$data['i'] = ($page * $params['limit'])- $params['limit'];
$data['pagination'] = $pagination;
return view('adminorders.public.index',$data);
}
}
function postSavepublic( Request $request)
{
$rules = $this->validateForm();
$validator = Validator::make($request->all(), $rules);
if ($validator->passes()) {
$data = $this->validatePost('tb_orders');
$this->model->insertRow($data , $request->input('SiparisID'));
return Redirect::back()->with('messagetext','<p class="alert alert-success">'.\Lang::get('core.note_success').'</p>')->with('msgstatus','success');
} else {
return Redirect::back()->with('messagetext','<p class="alert alert-danger">'.\Lang::get('core.note_error').'</p>')->with('msgstatus','error')
->withErrors($validator)->withInput();
}
}
}

Fatal error: Call to a member function selectCollection() on a non-object in C:\xampp\htdocs\phpmongodb\db.php

Can someone please help me, I get this fatal error message when I try to run the code in a browser. I have searched through various topics and couldn't find the answer. I have two very similar functions and only one of them is reporting an error. Function getById is working just fine, but function get reports an error. Here's my db.php file:
class DB {
private $db;
public $limit = 5;
public function __construct($config){
$this->connect($config);
}
private function connect($config){
try{
if ( !class_exists('Mongo')){
echo ("The MongoDB PECL extension has not been installed or enabled");
return false;
}
$connection= new MongoClient($config['connection_string'],array('username'=>$config['username'],'password'=>$config['password']));
return $this->db = $connection->selectDB($config['dbname']);
}catch(Exception $e) {
return false;
}
}
public function create($collection,$article){
$table = $this->db->selectCollection($collection);
return $result = $table->insert($article);
}
public function get($page,$collection){
$currentPage = $page;
$articlesPerPage = $this->limit;
//number of article to skip from beginning
$skip = ($currentPage - 1) * $articlesPerPage;
$table = $this->db->selectCollection($collection); **//here reports an error**
$cursor = $table->find();
//total number of articles in database
$totalArticles = $cursor->count();
//total number of pages to display
$totalPages = (int) ceil($totalArticles / $articlesPerPage);
$cursor->sort(array('saved_at' => -1))->skip($skip)->limit($articlesPerPage);
//$cursor = iterator_to_array($cursor);
$data=array($currentPage,$totalPages,$cursor);
return $data;
}
public function getById($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new MongoId($id);
}
$table = $this->db->selectCollection($collection);
$cursor = $table->find(array('_id' => $id));
$article = $cursor->getNext();
if (!$article ){
return false ;
}
return $article;
}
public function delete($id,$collection){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->remove(array('_id'=>$id));
if (!$id){
return false;
}
return $result;
}
public function update($id,$collection,$article){
// Convert strings of right length to MongoID
if (strlen($id) == 24){
$id = new \MongoId($id);
}
$table = $this->db->selectCollection($collection);
$result = $table->update(
array('_id' => new \MongoId($id)),
array('$set' => $article)
);
if (!$id){
return false;
}
return $result;
}
public function commentId($id,$collection,$comment){
$postCollection = $this->db->selectCollection($collection);
$post = $postCollection->findOne(array('_id' => new \MongoId($id)));
if (isset($post['comments'])) {
$comments = $post['comments'];
}else{
$comments = array();
}
array_push($comments, $comment);
return $postCollection->update(
array('_id' => new \MongoId($id)),
array('$set' => array('comments' => $comments))
);
}
}

Codeigniter: Validate form field on edit

I am having trouble and since more than a week trying to find a solution to disallow duplicate form content if it is already exists in database.
So it will check all rows excluding the id (row) what currently I am editing and if same value exists it should give error message.
Here is my Code.
Position Controller
public function position_edit($id = NULL)
{
$this->data['title'] = '<i class="fa fa-user"></i> ' . lang('position_edit');
$this->data['position'] = $this->positions_model->get($id);
count($this->data['position']) || $this->data['errors'][] = 'position could not be found';
$id = $this->uri->segment(4);
$this->db->where('position', $this->input->post('position'));
!$id || $this->db->where('id !=', $id);
$pos = $this->positions_model->get();
echo '<pre>', print_r($pos), '</pre>';
if (count($pos) > 0) {
$this->form_validation->set_rules('position', 'lang:position_code', 'trim|required|max_length[10]|is_unique[positions.position]|xss_clean');
$this->form_validation->set_message('is_unique', lang('error_position_exists'));
}
if ($this->form_validation->run() === TRUE) {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
//redirect('admin/hr/positions', 'refresh');
}
// Load the view
$this->load->view('hr/positions/edit', $this->data);
}
Position Model
class Positions_Model extends MY_Model
{
protected $_table_name = 'positions';
protected $_order_by = 'label ASC';
// This $rules currently not in use since it has been
// set directly to the controller edit method code
public $rules = array(
'position' => array(
'field' => 'position',
'label' => 'Position Code',
'rules' => 'trim|required|max_length[10]|xss_clean'
),
'label' => array(
'field' => 'label',
'label' => 'Position Label',
'rules' => 'trim|required|max_length[50]|xss_clean'
),
);
public function get_new()
{
$position = new stdClass();
$position->position = '';
$position->label = '';
return $position;
}
public function get_positions($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
return parent::get($id, $single);
}
public function get_positions_array($id = NULL, $single = FALSE)
{
$this->db->get($this->_table_name);
$positions = parent::get($id, $single);
$array = array();
foreach($positions as $pos){
$array[] = get_object_vars($pos);
}
return $array;
}
public function delete($id)
{
// Delete a position
parent::delete($id);
}
}
DB Model
class MY_Model extends CI_Model
{
protected $_table_name = '';
protected $_primary_key = 'id';
protected $_primary_filter = 'intval';
protected $_order_by = '';
public $rules = array();
protected $_timestamps = FALSE;
function __construct()
{
parent::__construct();
}
public function array_from_post($fields)
{
$data = array();
foreach ($fields as $field) {
$data[$field] = $this->input->post($field);
}
return $data;
}
public function get($id = NULL, $single = FALSE)
{
if($id != NULL) {
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->where($this->_primary_key, $id);
$method = 'row';
} elseif($single == TRUE) {
$method = 'row';
} else {
$method = 'result';
}
if(!count($this->db->ar_orderby)) {
$this->db->Order_by($this->_order_by);
}
return $this->db->get($this->_table_name)->$method();
}
public function get_by($where, $single = FALSE)
{
$this->db->where($where);
return $this->get(NULL, $single);
}
public function save($data, $id = NULL)
{
// Set timestamps
if ($this->_timestamps == TRUE) {
$now = date('Y-m-d H:i:s');
$id || $data['created'] = $now;
$data['modified'] = $now;
}
// Insert
if ($id === NULL) {
!isset($data[$this->_primary_key]) || $data[$this->_primary_key] = NULL;
$this->db->set($data);
$this->db->insert($this->_table_name);
$id = $this->db->insert_id();
} else {
// Update
$filter = $this->_primary_filter;
$id = $filter($id);
$this->db->set($data);
$this->db->where($this->_primary_key, $id);
$this->db->update($this->_table_name);
}
return $id;
}
public function delete($id)
{
$filter = $this->_primary_filter;
$id = $filter($id);
if (!$id) {
return FALSE;
}
$this->db->where($this->_primary_key, $id);
$this->db->limit(1);
$this->db->delete($this->_table_name);
}
}
I have tried callback function also but it is not working at all and couldn't find what causing the issue.
EDIT:
Please note it The above code is giving message if I am inserting the value which already exists but it is not validating and storing the data if the row is not exists
Updated
if ($this->form_validation->run() === TRUE) {
//print_r($this->positions_model->unique_value('position', $this->uri->segment(4)));
if($this->positions_model->unique_value('position', $this->uri->segment(4))) {
$this->form_validation->set_message('unique_value', lang('error_position_exists'));
} else {
$data = $this->positions_model->array_from_post(array('position', 'label'));
$this->positions_model->save($data, $id);
$this->session->set_flashdata('message', lang('position_record_updated'));
$this->data['message'] = $this->session->flashdata('message');
$this->session->set_flashdata('message_type', 'success');
$this->data['message_type'] = $this->session->flashdata('message_type');
redirect('admin/hr/positions', 'refresh');
}
}
In Controller
public function unique_value($field, $id)
{
$id = $this->uri->segment(4);
$this->db->where($field, $this->input->post($field));
!$id || $this->db->where('id !=', $id);
$position = $this->positions_model->get();
if (count($position)) {
return TRUE;
}
return FALSE;
}
Please Note: I don't know what exactly happens to your code, but I wouldn't check between insert or update into the model, just in the controller
I would solve it using a checkExist Model function, that would check if all the values you want to check exists into the DDBB, and work according to it. I would also do it in the controller instead of the model. First, you validate the fields, and then you check if values exists excluding the edit id:
$values_from_post = $this->positions_model->array_from_post(array('position', 'label'));
// $editId is to avoid the id of the row you were editing
if ($this->form_validation->run() === TRUE ) {
if ( !$this->positions_model->check_duplicate( $values_from_post, $editId ) ) ){
// Insert Value
} else {
// Update Value
}
And in your model, you check the duplicate via a where if the values exists:
public function check_duplicate( $values_from_post, $editId ) {
foreach ( $values_from_post as $key => $value ) {
$this->db->where( $key, $value );
}
$this->db->where('id !=', $editId );
$result = $this->db->get($this->_table_name);
return ( ( $result->num_rows > 0 ) ? true : false );
}
Please, I didn't check the code, but that is the idea, instead of doing it in the model, control it in the controller and then insert or update depending of what happens.
Here is the default validation rule of CodeIgniter for checking the duplicate entries in two columns.
$this->form_validation->set_rules('form_field_name','Title here','required|max_length[255]|unique[table.table_column1,table.table_column2]');

Add code snippet into a class

I have some function which I use in my cart application:
session_start();
if(!isset($_SESSION['products'], $_SESSION['price'], $_SESSION['product_names'],$_SESSION['product_id'])) {
$_SESSION['products'] = 0;
$_SESSION['price'] = 0;
$_SESSION['product_names'] = array();
$_SESSION['product_id'] = array();
}
if(isset($_POST['add'])) {
$_SESSION['product_names'][] = $_POST['product_name'];
$_SESSION['products']++;
$_SESSION['price'] += $_POST['price'];
}
if(isset($_POST['empty'])) {
session_destroy();
header('Location:index.php');
}
The question is, how can I add this into a class and call it in my view page?
I mean it will still work as <?php echo $_SESSION['price']?>. How can I make this work?
Try this class you're doing in a wrong way.
session_start();
class Shopping {
public function __construct()
{
}
//get cart products
public function getCartProducts()
{
$cart = array();
if(isset($_SESSION['cart'])) {
$cart = unserialize($_SESSION['cart']);
}
return $cart;
}
//add product to cart
public function addToCart($product_details)
{
$cart = $this->getCartProducts();
$product_id = $product_details['product_id'];
$is_quantity = $this->addQuantity($product_id); //check if product already exists in session if then increase the quantity
if(!$is_quantity) {
$product_details = array(
'qty' => $product_details['qty'],
'price' => $product_details['price'],
'product_name' => $product_details['name'],
'product_id' => $product_id
);
array_push($cart, $product_details);
$_SESSION['cart'] = serialize($cart);
}
}
//add quantity if product already exists
private function addQuantity($product_id)
{
$cart = $this->getCartProducts();
$i = 0;
foreach ($cart as $product) {
if($product['product_id'] == $product_id)
{
$product['qty'] += 1;
$cart[$i] = $product;
$_SESSION['cart'] = serialize($cart);
return true;
}
$i++;
}
return false;
}
public function clearCart()
{
unset($_SESSION['cart']);
}
public function removeProduct($product_id)
{
$cart = $this->getCartProducts();
$new_cart = array();
foreach ($cart as $product) {
if($product['product_id'] != $product_id)
array_push($new_cart, $product);
}
$_SESSION['cart'] = serialize($new_cart);
}
}
$shop = new Shopping();
$shop->addToCart(array('product_id'=>1,'name'=>'test 1','price'=>'120.00','qty'=>1));
$shop->addToCart(array('product_id'=>3,'name'=>'test 2','price'=>'120.00','qty'=>1));
This is an example of my approach using session in class. References work pretty well.
class Cart {
private $container ;
public function __construct(&$container){
if (!isset($container) || !is_array($container))
$session['cart'] = array() ;
$this->container = &$container ;
}
public function productExists($id){
return (isset($this->container[$id])) ;
}
}
$cart = new Cart($_SESSION['cart']) ;
At this point all changes in container can be performed in $_SESSION['cart'] . The rest of session array is not affected, that should be safe.

Categories