2014-02-10 32 views
1

我正在學習PHP。這是源代碼。

<?php 
$text = $_POST['text']; 

echo $text; 
?> 

<form action="index.php" method="post"> 
<input type="text" name="text" /> 
    <input type="submit"> 
</form> 

這是結果。我不知道問題在哪裏。

注意:未定義指數:文本C:\ XAMPP \ htdocs中\上線費薩爾\的index.php 2

+6

假設這是index.php,當您第一次運行腳本時,沒有任何內容被髮布。當你提交它應該工作。 – enapupe

+1

該死的男人,現在你有四個相同的答案!恭喜! –

回答

4

這意味着什麼都沒有在$_POST['text'] -後並不會出現,直到表格已提交。您需要使用isset()檢查:

<?php 
if(isset($_POST['text'])) { 
    $text = $_POST['text']; 

    echo $text; 
} 
?> 

<form action="index.php" method="post"> 
<input type="text" name="text" /> 
    <input type="submit"> 
</form> 
4

當你第一次去的網頁你的特殊變量「$ _ POST」是空的,這就是爲什麼你得到一個錯誤。您需要檢查是否有任何內容。

<?php 
$text = ''; 
if(isset($_POST['text'])) 
{ 
    $text = $_POST['text']; 
} 

echo 'The value of text is: '. $text; 
?> 

<form action="index.php" method="post"> 
    <input type="text" name="text" /> 
    <input type="submit"> 
</form> 
3

$_POST['text']僅在提交表單時填充。所以當第一次加載頁面時,它不存在,你會得到那個錯誤。爲了彌補您需要檢查瀏覽F的形式執行你的PHP的其餘部分之前提交:

<?php 
if ('POST' === $_SERVER['REQUEST_METHOD']) { 
    $text = $_POST['text']; 

    echo $text; 
} 
?> 

<form action="index.php" method="post"> 
<input type="text" name="text" /> 
    <input type="submit"> 
</form> 
2

您pprobably有如果表單已提交或不detemine。

<?php 
if (isset($_POST['text'])) { 
    $text = $_POST['text']; 
    echo $text; 
} 
?> 

<form action="index.php" method="post"> 
<input type="text" name="text" /> 
    <input type="submit"> 
</form> 

另外,您也可以使用$_SERVER['REQUEST_METHOD']

if ($_SERVER['REQUEST_METHOD'] == 'POST') {... 
+0

$ _POST始終設置。 – enapupe

+0

感謝您的建議......當然,您完全正確。 –

0

我們必須檢查用戶是否點擊了提交按鈕,如果是,那麼我們必須設置$ test變量。如果我們不使用isset()方法,我們總會得到錯誤。

<?php 
if(isset($_POST['submit'])) 
{ 
    $text = $_POST['text']; 
    echo $text; 
} 
?> 

<form action="index.php" method="post"> 
<input type="text" name="text" /> 
    <input type="submit" name="submit" value="submit"> 
</form>