2014-10-12 141 views
0

所以,我有一個PHP類,它有一個更新會話變量$_SESSION['location']的方法。但問題是,每次調用該方法時,都找不到保存的會話變量,並告訴我它未設置。它應該存儲一個位置ID,並且該方法根據會話變量從MySQL數據庫中提取下一個位置,然後存儲新的ID。但是SQL代碼中應該包含變量的地方是空的。PHP會話在刷新時不保存

我確實在頁面的開頭有session_start()。我試過手動設置變量,它也沒有做任何事情。還嘗試從另一個PHP頁面訪問該變量,也沒有運氣。請幫忙。

我的代碼的小樣本:

class location { 
@session_start(); 
function compass($dir) { 
    $select = $_SESSION['location']; 

    if($dir == "north") { 
     $currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat"); 
     $currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon"); 
     $sql = "[THE SQL CODE THAT GETS THE NEXT LOCATION]"; 
     $id = mysql_result(mysql_query($sql), 0, "id"); 

     $_SESSION['location'] = $id; 

     $return['loc']  = $this->display_location($id); 
     $return['lat']  = $this->display_lat($id); 
     $return['long']  = $this->display_long($id); 
     $return['id']  = $id; 
    } 

    return $return; 
} 
} 
+1

請張貼您的代碼。 – Ejaz 2014-10-12 01:14:00

+2

你應該把'session_start();'放在類外的頁面頂部。它應該只在加載時包含在頁面中。你在哪裏設置'$ _SESSION ['location']'? – Rasclatt 2014-10-12 01:19:11

+2

這就是爲什麼很少使用錯誤抑制(@)並且僅用於非常特定的目的的一個示例。 – Devon 2014-10-12 01:20:48

回答

0

我已經在這個文件中測試你的代碼

**不要使用session_start()。

對於簡單測試,首先將其添加到compass()函數中。

$_SESSION['location'] .= 'World'; 

然後用這些代碼創建一個php腳本。

<?php 
    session_start(); 
    $_SESSION['location'] = 'Hello'; 
    include_once('*your name of class file*'); 
    $obj = new location(); 
    $obj -> compass('north'); 
    echo $_SESSION['location']; 
?> 

運行此腳本

如果輸出的 「HelloWorld」,那麼你的$ _SESSION [ '位置']工作。

0

檢查您的phpinfo(),以查看是否定義了會話保存路徑。如果不是,請定義一個目錄來存儲會話。在您的代碼中:

session_save_path('/ DIRECTORY IN YOUR SERVER');

然後再試一次。

+0

是的,所有的會話變量都在工作,除了這一個。 – Thomas 2014-10-12 08:26:21

0

這更接近你的方法應該看起來像。有一些設置可以幫助減少運行該功能時出現的錯誤。有了這個功能和其他建議,你應該能夠消除你得到的錯誤。

class location 
    { 
     public function compass($dir = '') 
      { 
       // Set the $select by $_SESSION or by your function 
       $select = (isset($_SESSION['location']))? $_SESSION['location']: $this->myFunctionToSetDefault(); 

       // I set $dir to empty so not to throw error 
       if($dir == "north") { 
         $currentlat = mysql_result(mysql_query("SELECT `lat` FROM `locationdb` WHERE id=".$select), 0, "lat"); 
         $currentlon = mysql_result(mysql_query("SELECT `lon` FROM `locationdb` WHERE id=".$select), 0, "lon"); 
         $sql  = "[THE SQL CODE THAT GETS THE NEXT LOCATION]"; 
         $id   = mysql_result(mysql_query($sql), 0, "id"); 

         $_SESSION['location'] = $id; 
         $return['loc']   = $this->display_location($id); 
         $return['lat']   = $this->display_lat($id); 
         $return['long']   = $this->display_long($id); 
         $return['id']   = $id; 
        } 

       // This will return empty otherwise may throw error if $return is not set 
       return (isset($return))? $return:''; 
      } 
    }