消息"Notice: Undefined index: ..."



我知道这个问题被问了太多次了。我试图通过这些帖子解决我的错误,但它们对我不起作用。

在这里,我尝试在MySQL数据库上使用HTML和PHP代码存储用户名和密码。我也在使用XAMPP。

我的浏览器向我显示如下错误:

Notice: Undefined index: username in C:xampphtdocsYCconect.php on line 7
Notice: Undefined index: username in C:xampphtdocsYCconect.php on line 9
Username should not be empty

HTML 代码如下:

<!DOCTYPE html>
<html>
<head>
<title>Form site</title>
</head>
<body>
<form align="center" method="post" action="conect.php">
Username : <input type="text" name="username"><br><br>
Password : <input type="password" name="password"><br><br>
<input type="submit" name="" value="Submit">
</form>
</body>
</html>

我的PHP代码conect.php

<?php
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "youtube";
$username = $_POST['username'];
$username = $_POST['username'];
// Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (empty($username))
{
echo "Username should not be empty";
die();
}
if (empty($password))
{
echo "Password should not be empty";
die();
}
$sql = "INSERT INTO account (username, password) values ('$username',
'$password')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

这是我第一次使用 PHP 代码连接 MySQL 数据库。

我该如何解决这个问题?

尝试以下格式。这可能会对您有所帮助。

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (isset($username) && !empty($username))
{
if (isset($password) && !empty($password))
{
$host = "localhost";
$dbusername = "root";
$dbpassword = "";
$dbname = "youtube";
// Create connection
$conn = new mysqli($host, $dbusername, $dbpassword, $dbname);
// Check connection
if (mysqli_connect_error())
{
die('Connect Error (' . mysqli_connect_errno() . ') ' .
mysqli_connect_error());
}
else
{
$sql = "INSERT INTO account (username, password) values ('$username','$password')";
if ($conn->query($sql))
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
}
else
{
echo "Password should not be empty";
die();
}
}
else
{
echo "Username should not be empty";
die();
}
}
?>

打印$_post并检查用户名索引是否可用于此$_post

print_r($_POST)

最新更新