PHP $_POST 错误请帮帮我,我正在学习 PHP

PHP $_POST error Please Help me I am learning PHP

提问人:user3294383 提问时间:2/11/2014 更新时间:2/11/2014 访问量:263

问:

我正在学习PHP。这是源代码。

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

echo $text;
?>

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

这是结果。我不知道问题出在哪里。

注意:未定义的索引:第 2 行 C:\xampp\htdocs\faisal\index.php 中的文本

php html mysql post undefined-index

评论

6赞 enapupe 2/11/2014
假设这是索引.php,当您第一次运行脚本时,没有发布任何内容。当你提交时,它应该可以工作。
1赞 Joe RR 2/11/2014
该死的,现在你有四个相等的答案!祝贺!

答:

4赞 elixenide 2/11/2014 #1

这意味着里面什么都没有——而且不会有,直到表格提交之后。您需要用于检查:$_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赞 Tutelage Systems 2/11/2014 #2

当您第一次转到该页面时,您的特殊变量“$_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赞 John Conde 2/11/2014 #3

$_POST['text']仅在提交表单时填充。因此,当页面首次加载时,它不存在,并且您会收到该错误。为了补偿,您需要在执行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赞 Markus Kottländer 2/11/2014 #4

您可能必须确定表格是否已提交。

<?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赞 enapupe 2/11/2014
始终设置 _POST 美元。
0赞 Markus Kottländer 2/11/2014
感谢您的推荐...当然,这是你完全正确的。
0赞 Pank 2/11/2014 #5

我们必须检查用户是否点击了提交按钮,如果是,那么我们必须设置$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>