2016-03-03 78 views
-4

我需要一些關於如何使用POST傳遞變量而不使用會話的幫助。爲什麼PHP不使用在POST之外聲明的變量?

目前我的代碼並不顯示變量的值稱爲$ MYVARIABLE:

<?php 
if(isset($_POST['testbutton'])){ 
if ($_POST['testbutton'] == 'Testing') { 

echo $myvariable; 
var_dump($_POST); 

} 
} 

$myvariable = "hello world"; 

echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">'; 
echo '<input type="submit" value="Testing" name="testbutton"/>'; 
echo '</form>'; 

?> 

我應該在更改代碼能在POST使用變量$ [「testbutton」]的一部分代碼?

+2

您正在嘗試在定義它之前調用'$ myvariable'。移動 '$ myvariable =「hello world」;'頂部 – WheatBeak

+2

定義它_before_您嘗試使用它 – jmoerdyk

+2

移動'$ myvariable =「hello world」;'頂部 – devpro

回答

2

每我的評論:

<?php 

$myvariable = "hello world"; 

if(isset($_POST['testbutton'])){ 
    if ($_POST['testbutton'] == 'Testing') { 

     echo $myvariable; 
     var_dump($_POST); 

    } 
} 



echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">'; 
echo '<input type="submit" value="Testing" name="testbutton"/>'; 
echo '</form>'; 

?> 

UPDATE

如果你想要做的是從頁面傳遞變量$_POST你需要做的是吉榮建議,並設置這樣一個隱藏的輸入:

echo '<input type="hidden" value="' . $myvariable .'" name="myvariable"/>'; 

這將進而成爲$_POST["myvariable"]

+1

我不認爲這是OP所需要的,但是這個問題並不完全清楚...... – jeroen

+0

我認爲沒有必要使用這個'if($ _POST ['testbutton'] =='Testing'){' – devpro

+0

謝謝你的幫助。 –

2
<?php 

// define $mvvariable here and PHP will not bring undefined error 
$myvariable = "hello world"; 

if(isset($_POST['testbutton'])){ 
if ($_POST['testbutton'] == 'Testing') { 

echo $myvariable; 
var_dump($_POST); 

} 
} 


echo '<form action="'.htmlspecialchars($_SERVER["PHP_SELF"]).'" method="post">'; 
echo '<input type="submit" value="Testing" name="testbutton"/>'; 
echo '</form>'; 

?> 
相關問題