<!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
表中。
如果您尝试访问不存在的数组元素,则会发出未定义的索引通知。例如:
$my_array = array(
"name" => "Joe",
"age" => 30
);
echo $my_array["languages"]; // notice emitted; "languages" does not exist
在您的情况下,您是在$_POST
而不是在您创建的阵列上访问它,但同样的原因适用。在您的情况下,这是因为您在 HTML 中将username
拼写错误为useraname
,因此尝试访问 username
的值将不起作用。
您的输入名称属性中有拼写错误
<input type="text" name="useraname" />
应该是
<input type="text" name="username" />
为避免插入空用户名和密码,您可以使用:
if(isset($_POST["add"]) && isset($_POST['username']) && isset($_POST['password'])){
//your code
}
> 您正在尝试访问用户名$username = $_POST["username"]
,但您没有,请查看
<input type="text" name="useraname" />
你有一个错别字。这就是用户名未定义的原因。