【发布时间】:2012-05-13 23:27:11
【问题描述】:
可能重复:
strange php error
Submit an HTML form with empty checkboxes
PHP form checkbox and undefined index
以下代码中出现未定义索引错误的某些原因。任何帮助,将不胜感激。这是我收到的错误
Notice: Undefined index: username in C:\xampp\htdocs\register.php on line 5
Notice: Undefined index: password in C:\xampp\htdocs\register.php on line 6
Notice: Undefined index: firstname in C:\xampp\htdocs\register.php on line 7
Notice: Undefined index: surname in C:\xampp\htdocs\register.php on line 8
代码:
<?php
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("clubresults") or die(mysql_error());
$username = $_POST['username'];
$password = md5($_POST['password']);
$firstname = $_POST['firstname'];
$surname = $_POST['surname'];
$sql = "INSERT INTO members (Username, Password, Firstname, Surname) VALUES ($username, $password, $firstname, $surname);";
mysql_query($sql);
?>
<html>
<div class="content">
<center>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<table border="0">
<tr><td colspan=2><h1>Register</h1></td></tr>
<tr><td>Username:</td><td>
<input type="text" name="username" maxlength="60">
</td></tr>
<tr><td>Password:</td><td>
<input type="password" name="password" maxlength="10">
</td></tr>
<tr><td>Firstname:</td><td>
<input type="text" name="firstname" maxlength=210">
</td></tr>
<tr><td>Surname:</td><td>
<input type="text" name="surname" maxlength=210">
</td></tr>
<tr><th colspan=2><input type="submit" name="submit"
value="Register"> </th></tr> </table>
</form>
</center>
</div>
</html>
【问题讨论】:
-
请停止使用古老的
mysql_*函数编写新代码。它们不再维护,社区已经开始 deprecation process 。相反,您应该了解prepared statements 并使用PDO 或MySQLi。如果您无法决定,this article 将帮助您选择。如果你想学习,here is a good PDO-related tutorial. -
检查链接问题的解决方案,它可能会有所帮助。
-
您的代码假定这些值存在。当表格发布时,他们会。但是当页面最初加载时,它们不会。查看
isset()函数以检查数组中的值是否存在,然后再尝试使用该值。 -
我不喜欢的一件事是在不需要的地方缩短 url,另一件事是在数组出现问题时询问 sql。修改你的
$_POST -
您可以设置空值来形成
$_SERVER['PHP_SELF']的动作