2013-02-07 145 views
0

當我檢查我的cookie時,我確實看到PHPSESSID正在製作。但是當我嘗試使用它們時,我收到一條錯誤消息,說該變量未定義。無法創建動態變量

這是我怎麼設置我的會議:

$posts = array("auto_year", "auto_brand", "auto_model", "auto_bodywork", "auto_doors", 
"auto_fuel", "auto_gearbox", "auto_type", "auto_uitvoering", "auto_part", "auto_description", "email_address"); 

//Define POSTS and set into SESSIONS 
foreach ($posts as $post) { 
    if (isset($_POST[$post])) { 
     $_SESSION[$post] = $_POST[$post]; 
     $$post = $_SESSION[$post]; 
    } 
} 

我也試過手動像:

$_SESSION['auto_year'] = '2012'; 

但它仍然無法正常工作。我確實在兩個頁面的頂部都調用了session_start(),但它一直給我提供那個錯誤。

+0

哪個變量是未定義的? –

+0

使用該foreach進行的所有變量。所以$ auto_year,$ auto_brand等等 –

+0

如果在for循環之後執行'var_dump($ _ SESSION)',會發生什麼? – Jim

回答

0

這可能是錯誤的$ _POST數據來自您的表單。由於我沒有表單信息,我試圖通過設置$ _POST。

session_start(); 

$_POST['auto_year'] = 1977; 

$posts = array("auto_year", "auto_brand", "auto_model", "auto_bodywork", "auto_doors", 
    "auto_fuel", "auto_gearbox", "auto_type", "auto_uitvoering", "auto_part", "auto_description", "email_address"); 

//Define POSTS and set into SESSIONS 
foreach ($posts as $post) { 
    echo $post."<br>"; 
    if (isset($_POST[$post])) { 
echo "Creating variable for $post<br>"; 
     $_SESSION[$post] = $_POST[$post]; 
     $$post = $_SESSION[$post]; 
     echo '$auto_year: '.$auto_year . "<br>"; 
    } 
} 
echo "<br><br>".var_dump($_SESSION); 
+0

除此部分外,一切正常:$$ post = $ _SESSION [$ post];它不會將它們扔到變量中,例如$ auto_year。帖子被設置並且會話也被設置。 –

1

使用${}您可以創建動態變量。在你的情況下,只需更改爲:

${$post} = $_SESSION[$post];

+0

理想情況下'$$ post = $ _SESSION [$ post];'應該也能工作! – SparKot

+0

我注意到這些變量是在其他頁面無法訪問的地方進行的。它在if($ submit)語句中,另一個在另一個語句中提交。他們在同一個文件中,所以我沒有這樣想過。對不起,我的愚蠢的錯誤。 –

0

另一種選擇是創建一個使用提取物(),它使您可以設置在一氣呵成的所有變量的變量;

extract($_SESSION); 

將爲會話中的每個鍵創建一個變量,例如, $ auto_year,$ auto_brand等

http://php.net/manual/en/function.extract.php

我不知道爲什麼你要在不同的變量的所有數據,而一個關聯數組可能是一樣容易處理?