注意:未定义的索引

时间:2013-12-30 22:08:57

标签: php html

我正在尝试学习PHP。我无法运行这个例子。但我认为代码是真的。我在我的localhost尝试它。我可以运行它吗?

<html>
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8" />
<title>My Page</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name"fname">
<input type="submit">
</form>
<?php
$name=$_REQUEST['fname'];
echo $name;
?>
</body>
</html>

错误: (!)注意:未定义的索引:第12行的C:\ wamp \ www \ index.php中的fname

3 个答案:

答案 0 :(得分:1)

您尚未提交表单,因此$_POST['fname']不存在。试试这个:

<?php
// turns off all errors and notices, recommended for a production website
// comment out this code if on development environment, it will make you a better programmer
error_reporting(0);
?>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/HTML; charset=utf-8" />
        <title>My Page</title>
    </head>
    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
            Name: <input type="text" name"fname">
            <input type="submit">
        </form>
        <?php
        if(isset($_REQUEST['fname']))
        {
            echo $_REQUEST['fname'];
        }
        ?>
    </body>
</html>

答案 1 :(得分:0)

<html>
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=utf-8" />
<title>My Page</title>
</head>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if(isset($_POST['fname'])){
$name=$_POST['fname'];
echo $name;
}
?>
</body>
</html>

答案 2 :(得分:0)

您需要检查变量是否已设置,否则您将收到该错误消息。 做类似的事情:

<html>

    <head>
        <meta http-equiv="Content-Type" content="text/HTML; charset=utf-8" />
        <title>My Page</title>
    </head>

    <body>
        <form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">Name:
            <input type="text" name "fname">
            <input type="submit">
        </form>
        <?php 
             if (isset($_REQUEST['fname'])) {
                 $name = $_REQUEST[ 'fname']; 
                 echo $name; 
             }
        ?>
    </body>

</html>