I am a still a newbie when it comes to using YII, but I been working with session variables for the past few days, and I can't seem to grasp to the concept behind my error. Any advice will be appreciated.
My add function works perfectly so far, for my current purpose of keeping track of the last 3 variables added to my session variable nutrition.
public function addSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
Yii::app()->session['nutrition'] = array();
}
$nutrition = Yii::app()->session['nutrition'];
array_unshift($nutrition, $pageId);
array_splice($nutrition, 3);
Yii::app()->session['nutrition'] = $nutrition;
}
My remove function doesn't seem to work at all, no matter what I try to do with it. The reason why I am transfering the session array to a temp array was to try to get around the "If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called." But it was a total failure.
public function removeSessionFavourite($pageId)
{
$page = Page::model()->findByPk($pageId);
$categoryName = $page->getCategoryNames();
if($categoryName[0] == 'Nutrition')
{
if(!isset(Yii::app()->session['nutrition']))
{
return true;
}
$nutritionArray = Yii::app()->session['nutrition'];
unset($nutritionArray[$pageId]);
Yii::app()->session['nutrition'] = $nutritionArray;
}
Any advice or push toward to the correct direction will be appreciated.
I personally I have never used Yii::app()->session I normally use the Yii user and I have never had any issues with it:
Yii::app()->user->setState('test', array('a'=>1,'b'=>2));
print_r(Yii::app()->user->getState('test')); //see whole array
$test = Yii::app()->user->getState('test');
unset($test['b']);
Yii::app()->user->setState('test',$test);
print_r(Yii::app()->user->getState('test')); //only 'a'=>1 remains
Yii::app()->user->setState('test', null);
print_r(Yii::app()->user->getState('test')); //now a null value
As I put in a comment above there seems to be issues with multidimensional arrays with the session variable: https://code.google.com/p/yii/issues/detail?id=1681
Related
[PHP 7.1]
Below you can see my PHP code. My problem comes from my difficult to understand why the second IF statement doesn't work with the array $_SESSION['items'], but does work with the testing array $zoo (I just created $zoo to make tests in place of $_SESSION['items']).
I've an AJAX script that send POST data to the PHP code and then logs the response to the browser console in order to let me review the results. Everything was working fine with my tests, all changes done to other arrays where executed with fine results, the only issue I couldn't understand and solve, even after extensively searching for some clues on the web and trying different things, is the misterious ways of the $_SESSION array that doesn't seem to like to expose its keys to lurking IF statements... And I got here trying to detect the existence of a key inside an array in order to increment its value. Something I already did before with other arrays that weren't $_SESSION arrays and it worked just fine.
session_start();
$_SESSION['items'] = array();
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['item_name'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
This is a simplified version of your code with just the important stuff
session_start();
$_SESSION['items'] = array(); //items is now emtpy
if (isset($_SESSION['items'][$_POST['item_name']]) || array_key_exists($_POST['item_name'], $_SESSION['items'])) {
}
This should make it a bit easier to see, so it's simply because items is an empty array. Do to assigning it as such before the condition.
To fix it, either remove this line:
$_SESSION['items'] = array();
OR better yet:
$_SESSION['items'] = isset($_SESSION['items']) ? $_SESSION['items'] : [];
OR even
if(!isset($_SESSION['items'])) $_SESSION['items'] = [];
It's up to you how you fix it, but I am certain you don't want to reset that to an empty array. It's a very easy mistake to make, and a hard one to find because it's technically legal PHP code. I just have a built in debugger in my head now, from years of coding ... lol ... Most times I can literally picture in my mind how something will execute.
Cheers!
As noted by #artisticphoenix -
session_start();
// Check to see if there is a session variable before clearing it
// You only want to initialize it once
if (!isset($_SESSION['items'])) {
$_SESSION['items'] = [];
}
$zoo['animals'] = array('tiger'=>2,'lion'=>3);
if(isset($_POST['item_name'])) {
// This test is sufficient to check if the session variable has been set
if (isset($_SESSION['items'][$_POST['item_name']])) {
$_SESSION['items'][$_POST['item_name']]['qnt']++;
} else {
$_SESSION['items'][$_POST['item_name']] = array('model'=>$_POST['item_model'], 'qnt'=>1);
}
echo json_encode($_SESSION['items']);
exit();
}
$_SESSION['item_name'] should be $_SESSION['items']
I have a series of variables in php:
move1A = $row['column'];
move2A = $row['column'];
move3A = $row['column'];
etc.
I want to create a variable that will represent these variables and check if it is NULL. I have spent quite a bit of time looking, and although I believe that variable variables may be the key to my problem. So far I have tried:
$current_move_check = 'move'.$moveCounter.'A';
and
$current_move_check = '$move'.$moveCounter.'A';
Neither seem to work. Any suggestions for making something like this work? Thanks!
UPDATE:
So I'm trying to loop the moveXA variables based on user input and I need to run different script whether it is null or set.
I thought that:
elseif (!$$current_move_check) {
and
elseif ($$current_move_check) {
would work but they seem to not be outputting as expected.
Considering your update, I'd really suggest you to use an array, rather than the variable variables trick. Your code would makes more sense and be easier to maintain :
$count = 0;
$moveA[++$count] = $row['column'];
$moveA[++$count] = $row[...];
$moveA[++$count] = $row[...];
...
foreach ($moveA as $key => $value) {
if ($value) { // = $$current_move_check
} else { // = !$$current_move_check
}
}
As #MatsLindh pointed out in its comment : "Variable variables are never a good idea. Unless you know when it makes sense to break that rule, don't."
$current_move_check = 'move'.$moveCounter.'A';
echo $$current_move_check;
now you can check this as well like
if($$current_move_check!=NULL)
{
// do your code
}
I've been at this for two hours, perhaps I could ask some help.
Alright, so I have a basic $_POST variable that a user submits. As you can see below, the code first checks if a value was submitted at all, and if not sets it to a default value. If the user did submit a value, it sets a variable (later used) to the value submitted. You can see my code below.
if(!isset($_POST['pSize'])) {
$pSize = "16";
}
else {
$pSize = ($_POST['pSize']);
};
echo $pSize;
The problem with the above is that I might have 50 or so different areas that the user will submit, and it'd be much nicer to just have myFunction('name','default','value'); than to write out the above for each area. However, I've been running into a problem. Here's a few examples of things I've tried. (excuse any minor errors; I don't have the actual code I tried, just the jist of what I was getting at. The problems of the code I had were not syntax errors).
function newFunction($title, $default, $value)
if(!isset($_POST[$value])) {
$title = $default;
}
else {
$title = ($_POST[$value]);
};
newFunction('pSize','16,'24');
echo $pSize;
I soon learned that the above won't work due to the fact that variables in a function won't be able to be used outside of that function unless they're global. That makes sense, since if the variable $title could be used, it would be set to many different things depending on how many times I called the function. These things in mind, I tried to set global variables.
function newFunction($title, $default, $value)
if(!isset($_POST[$value])) {
global $title . 'Title' = $title;
...
newFunction('pSize','16,'24');
echo $pSizeTitle;
I lastly tried to set the global variable to the name of the $title I supplied for the function with the string 'Title', creating the new global variable pSizeTitle, so I could echo that variable out. And this probably would have actually worked, except for the fact that I cannot define a global variable with something appended to the end, only with a simple name, and that will not work for me since I need a new global variable for every title item I have.
Hopefully this is clear, sorry if this is an absolute noob problem, I just really can't get past this.
I think the major problem is that you are not returning any data in your function, try to do it
function newFunction($title, $default, $value)
{
if(!isset($_POST[$value])) {
$title = $default;
} else {
$title = ($_POST[$value]);
}
return $title;
//return was missed
}
function checkDefault($index, $default)
{
return isset($_POST[$index]) ? $_POST[$index] : $default;
}
$title = checkDefault("title", "my default value");
I will be reusing a Drupal db_query result set unpacking function many, many times in my code for a variety of different queries - I am using O-O and as such I want to reuse it and be as 'DRY' as possible.
Therefore I have tried to strip it down to the most generic functions so that as long as the $columns supplied match the columns used in the query and similarly in the $resultset, I can loop and assign values to keys, as is shown, and return a $rows[].
I've not yet come across the issue of trying to use a variable's value as a variable name (the $key), if it's just something I should avoid entirely, please say.
foreach($this->resultSet as $aRecord) {
$c = 0;
while (isset($this->columns[$c])) {
$value = $this->columns[$c];
$rows[$i] = array(
$key[$this->columns[$c]] => $aRecord->$value,
);
$c++;
}
$i++;
}
I've read through the following and am beginning to think this is just knowledge I'm missing in my PHP experience so far.
Can I use a generated variable name in PHP?
PHP use function return value as array
https://wiki.php.net/rfc/functionarraydereferencing
It felt wrong, and someone once told me that if you have to start writing complex functions in PHP you've probably missed an available function PHP already offers.. so true... thanks to (at the time of writing...) 'MrCode' for this suggestion.
$this->sql = "SELECT foo, bar FROM foobar";
$this->result = db_query($this->sql);
if ($this->result->rowCount() > 0) {
while ($row = $this->result->fetchAssoc()) {
$this->resultArray[] = $row;
}
}
I have the following segment of code that someone else has written, and that I'm trying to fix:
function calc() {
require_once("db.php");
connect();
$a = split("#", $_SESSION['freight']);
$loc = $a[0];
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction () {
$_SESSION['freight'] = $_GET['loc'];
$freight = calc();
echo number_format($freight, 2);
return;
}
It ain't pretty, I am just trying to fix it.
Now I have noticed the bug seems to stem from the fact $freight = calc(). After that line, $freight will equal say $10 (the $arr['price'] value). BUT the $_SESSION['freight'] will also equal $10, and just $10, as if it was the same variable as $freight. What ever I set $freight to, the $_SESSION['freight'] also becomes.
If I change $freight in the ajax function to $freight2 it doesn't alter the session variable. Is this something major that I don't know about PHP? That variable names share the same namespace as session variables?
The question overall is:
Does changing $a alter $_SESSION['a'] in anyway? Because it really seems like it does.
It looks like your register globals is set to on in your php.ini file. You need to turn that off. If it's on, your $_SESSION, $_GET, $_POST elements can be referred to as the variable names.
e.g. $_SESSION['item'] is the same as $item
More info here: http://us2.php.net/manual/en/ini.core.php#ini.register-globals
Also, register globals is now deprecated, which also means that if this is indeed the issue, you were using an older version of PHP, and may want to consider upgrading.
As far as I can tell...
your $_SESSION variable should not be a session variable at all as it always equals $_SESSION['freight'] = $loc."#".$arr['price'];
I actually do not understand the use of the session so this is whow i would have approach it
function calc($loc)
{
require_once("db.php");
connect();
$r = mysql_query("SELECT `price`, `gst` FROM `freight` WHERE `location`='$loc'");
$arr = mysql_fetch_array($r);
$_SESSION['freight'] = $loc."#".$arr['price'];
return $arr['price'];
}
function ajaxFunction ()
{
$a = split("#", $_GET['loc']);
$freight = calc($a[0]);
echo number_format($freight, 2);
return;
}
You only need the location so that you can run your queries. So just set the session once with the new data from the database.
Hope that helps
I always use different notation for session variables. For example $_SESSION['_uid'] versus a regular $uid variable.