开发者

PHP variable name conflict with session variables

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 namespac开发者_JS百科e 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜