codeigniter array data in session - php

I started to learn codeigniter and now I have one prblem. I am making online store for laptops and now I have a wish to make a cart. I wanna remember all data in session when user add some laptop in cart, redardless is logged or not. But my problem is that I remember in session only last added id of laptops. I managed to remember number of laptops in total, and total price, but can’t manage how to remember all id. I am using next code in controller:
public function adding()
{
$id_lap=$this->input->post('id_lap'); // id laptop of which was clicked by user
$num_items=$this->input->post('num_items'); // total number of laptops
$price=$this->input->post('price'); // total cost
if($id_lap !='')
{
$this->session->set_userdata('num_items',$num_items);
$this->session->set_userdata('price_new',$price);
$this->session->set_userdata('id_lap_new',$id_lap);
$response=array(
'status'=>1,
'num_items'=>$num_items,
'price_new'=>$price,
'id_new_lap'=>$id_lap
);
} else {
$response=array(
'status'=>0
);
}
echo json_encode($response);
}
I am using Ajax for sending data in controller.
Thanks for answer, I appreciate.

try to save the session in the database, first open your config.php under application folder and change use session database option value to true. Import the sql structure like you have there and use sessions like you have. It will store the session variable in db. You might want to enable session encryption as well.

Related

Yii 1.1 session sometimes won't store value

I'm getting a weird behavior I can't fully explain. Consider this controller code:
public function actionCreate()
{
$order = new Order();
$this->performAjaxValidation($order, null, 'order-form');
if (isset($_POST['Order'])) {
$order->attributes = $_POST['Order'];
if ($order->save()) {
Yii::app()->session['order_id'] = $order->id;
$this->redirect('confirm');
}
}
$this->render('create', array('order' => $order));
}
public function actionConfirm()
{
$order_id = Yii::app()->session['order_id'];
if(!$order_id) {
throw new CHttpException(404, 'Order not found');
}
$order = $this->loadModel($order_id);
$this->render('confirm', array('order' => $order));
}
So first I create the order, then if creation is successful, there is a redirect to the confirmation page. Order id is saved to the session so the customer can see the order they created. Why can't I make a redirect to "confirm($order_id)" page? Because 1. Order contains user submitted data and it can't be public, only user created that order can view it on the confirmation page, and 2. There is no authentication there, users are not required to log in.
The weird thing is, most of the time it works fine, but sometimes (1 time out of 5 approx) the order id is not saved in session. If the session is fresh, then it will end up showing 404. If it's not and you create several orders, it will evenually show the previous order data (next order is saved fine).
I would suggest that something is wrong with the session component itself (I'm using CDbHttpSession). But everything else (session related stuff) is working fine on the site (backend auth never fails, flash messages always show up).
Any ideas where should I look?
Okay, it appears pretty obvious now. The reason was classic session race condition: session auto start, performAjaxValidation reads session before order_id is set, then saves session without order_id after order_id is set but before actionConfirm is called. Native PHP sessions are blocking so this situation won't happen but db sessions are not.

Setting cookie in codeigniter with one name and several values

I want to set a cookie in Codeigniter whenever the user clicks on "add to my favorites". But I'm confused. Because I have to add several items with one name at the same time. You know this is not possible and the CI overrides the previous values. Look at this:
$this->input->set_cookie(array("name"=>'fav', 'value'=>2500, 'expire'=>100000));
$this->input->set_cookie(array("name"=>'fav', 'value'=>3500, 'expire'=>100000));
$this->input->set_cookie(array("name"=>'fav', 'value'=>4500, 'expire'=>100000));
And when I try to get fav value using this function:
printer($this->input->cookie("fav"));
I get this result:
4500
How should I set a cookie for user when they ad an item to their favorite list so that in the moment of retrieving them I know what to retrieve. I cannot use database because this implementation is for the users who are not registered members.
You can use $this->session->set_userdata for storing values.
$fav = $this->session->userdata("my_favs");// get existing list
$fav[] = $new_fav; // append new items to list
$this->session->set_userdata(array("my_favs"=>$fav)); // update session with existing one.
To print all items
$fav = $this->session->userdata("my_favs")
foreach($fav as $fitems)
echo $fitems."<br/>";
I think you should use print_r() instead of printer().
more than that, you should use:
$this->input->get_cookie("fav");
Have a look here for more information: Cookie helper

PHP Cart with Object Oriented PHP

I am developing a simple system of sample products with Object Oriented PHP, very simple thing. So far, no problem, but I have to create a button that adds a product code recorded in the database to a form in the sidebar. I do not know to develop a shopping cart with OO PHP, and codes that I find always give error because of the call of the database, or when the data list. I've been thinking of doing for JS, any help?
sorry my bad english
I got it, first I did when I click a link step by GET and the ID Code I need after seto it in a cookie, each cookie with an ID. Then I check if cookie has registered with the IDs. Not the best and most correct, but it works (more or less). Now another problem, I need to click two times to get the result as it passes by id and need to be caught refresh = /
I think it was a bit confusing but it is the maximum that dyslexia allows me to do hehehe
Here I set up the structure with the data I have in my product page:
add
<?php
$cod_get = $_GET['cod'];
setcookie("SITENAME_cod_".$id_get."", $cod_get, time()+3600, "/","", 0);
?>
And here I have a loop checking if cookie with ids, I think it will give problems, but for now I think it works ...
Thank you all.
$produto = new produtos();
$i = 0;
$produto->selecionaTudo($produto);
$produto->selecionaCampos($produto);
while($res = $produto->retornaDados()):
$res->id;
$i++;
$get_cookie = $_COOKIE['SITENAME_cod_'.$res->id.''];
if (isset($get_cookie)) {
echo $get_cookie.', ';
}else{
echo "";
}
endwhile;

Get the store ID for multi store setup with opencart

We have a multi-store set up and I wanted to change the template slightly for each store. I had a good look through the code already in place and found these:
$this->config->get('config_store_id')
$this->load->model('setting/store');
$results = $this->model_setting_store->getStores();
$this->model_setting_setting->getSetting('config', $order_info['store_id']);
The first line only ever returns the default store ID. I would want this to work even if we have not order details.
What is the most reliable way to get the store ID?
The current store ID is in $this->config->get('config_store_id')
It gets changed to the correct store ID in this code in the index.php file
if ($store_query->num_rows) {
$config->set('config_store_id', $store_query->row['store_id']);
} else {
$config->set('config_store_id', 0);
}

Updating multiple page elements without refreshing the page using PHP & jQuery

I have a PHP page that uses jQuery to let a user update a particular item without needing to refresh the page. It is an availability update where they can change their availability for an event to Yes, No, or Maybe. Each time they click on the link the appropriate jQuery function is called to send data to a separate PHP file (update_avail.php) and the appropriate data is returned.
Yes
Then when clicked the params are sent to a PHP file which returns back:
No
Then, if clicked again the PHP will return:
Maybe
It all works fine and I'm loving it.
BUT--
I also have a total count at the bottom of the page that is PHP code to count the total number of users that have selected Yes as their availability by simply using:
<?php count($event1_accepted); ?>
How can I make it so that if a user changes their availability it will also update the count without needing to refresh the page?
My thoughts so far are:
$var = 1;
while ($var > 0) {
count($day1_accepted);
$var = 0;
exit;
}
Then add a line to my 'update_avail.php' (which gets sent data from the jQuery function) to make $var = 1
Any help would be great. I would like to stress that my main strength is PHP, not jQuery, so a PHP solution would be preferred, but if necessary I can tackle some simple jQuery.
Thanks!
In the response from update_avail.php return a JSON object with both your replacement html and your new counter value.
Or to keep it simple, if they click "yes" incriment the counter, if they click No or maybe and their previous action wasn't No or Maybe decrease the counter.
Assuming your users are logged into the system I'd recommend having a status field in the user table, perhaps as an enum with "offline", "available", "busy", "unavailable" or something similar and use the query the number of available users whilst updating the users status.
If you were to do this you'd need to include in extend your methods containing session)start() and session_destroy() to change the availability of the user to available / offline respectively
The best way is the one suggested by Scuzzy with some improvements.
In your php, get the count from the database and return a JSON object like:
{ count: 123, html: 'Yes' }
In your page, in the ajax response you get the values and update the elements:
...
success: function(data) {
$("#linkPlaceholder").html(data.html);
$("#countPlaceholder").html(data.count);
}
...

Categories