什么是未定义的索引错误?

时间:2013-07-20 23:18:44

标签: php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html>
<head>
</head>
<body>
<form method="POST">
<?php
//create connection
$dbh = new PDO('mysql:host=localhost;dbname=test', "root", "");
if(isset($_POST["add"])){
$username = $_POST["username"];
$password = $_POST["password"];
$std =$dbh->prepare("insert into new2 (username,password) values(?,?)");
$std->bindParam(1,$username);
$std->bindParam(2,$password);
$std->execute();
}
?>
username: <br />
<input type="text" name="useraname" />
<p>
password: <br />
<input type="text" name="password" />enter code here
<input type="submit" name="add" value="Add" />
</form>
</body>
</html>

这会导致以下错误:

 Undefined index: username in C:\wamp\www\bist\addtonew2.php on line 11

此类错误的原因是什么?我只是想在new2表中插入一些数据。

3 个答案:

答案 0 :(得分:1)

输入名称属性

中有拼写错误
<input type="text" name="useraname" />

应该是

<input type="text" name="username" />

为避免插入空用户名和密码,您可以使用:

if(isset($_POST["add"]) && isset($_POST['username']) && isset($_POST['password'])){
//your code
}

答案 1 :(得分:1)

如果尝试访问不存在的数组元素,则会发出未定义的索引通知。例如:

$my_array = array(
    "name" => "Joe",
    "age" => 30
);
echo $my_array["languages"];  // notice emitted; "languages" does not exist

在您的情况下,您在$_POST而不是在您创建的阵列上访问它,但同样的原因适用。在您的情况下,这是因为您在HTML中将username拼错为useraname,因此尝试访问username的值将无效。

答案 2 :(得分:0)

您正在尝试访问用户名$username = $_POST["username"],但您没有用户名,请查看

<input type="text" name="useraname" />
你有一个错字。这就是用户名未定义的原因。