我已经创建了一个简单的HTML登录页面。 我已经创建了一个PHP文件来将数据传输到MySQL数据库(使用MySQL Workbench 8.0) 但是,当我单击“提交”时,将打开一个页面,其中包含来自我的PHP文件的一些代码,并且没有数据传输到我的数据库中。 如何将数据从“登录”页面传输到MYSQL数据库?
我已将PHP文件保存在C://
登录页面代码:
<html>
<head>
<title>Login</title>
</head>
<body>
<form action="/Test1.php">
Username:<br>
<input type="text" value="username"><br>
Password:<br>
<input type="text" value="password"><br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
PHP代码:
<html>
<? php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (!empty($username)){
if (!empty($password)){
$host = "localhost:3306";
$dbusername = "root";
$dbpassword = "";
$dbname = "login";
// Create Connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
if (mysql_connect_error()){
die ( 'Connect Error ('.mysqli_connect_errno().')'.mysqli_connect_error());
}
else {
$sql = "INSERT INTO login.user (username, password)
values ('$username', '$password')";
if ($conn->query($sql)){
echo "New record is inserted 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();
}
?>
</html>
我希望将HTML文件中的数据输入到MYSQL数据库中,但是会打开一个新页面:
query($sql)){ echo "New record is inserted successfully"; } else { echo "Error:".$sql."
".$conn->error; } $conn->close(); } } else { echo "Password should not be empty"; die (); } else { echo "Username should not be empty"; die(); } ?>
答案 0 :(得分:0)
尝试一下:
<html>
<?php
$username = filter_input(INPUT_POST, 'username');
$password = filter_input(INPUT_POST, 'password');
if (empty($username)) {
echo 'Username should not be empty';
exit;
}
if (empty($password)) {
echo 'Password should not be empty';
exit;
}
$host = 'localhost:3306';
$dbusername = '';
$dbpassword = '';
$dbname = '';
// Create Connection
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli($host, $dbusername, $dbpassword, $dbname);
} catch (Exception $exception) {
exit('Error connecting to database');
}
$connection->set_charset('utf8mb4');
try {
$statement = $connection->prepare("INSERT INTO login.user (username, password) values (?, ?)");
$statement->bind_param('ss', $username, $password);
$statement->execute();
$statement->close();
echo 'New record is inserted successfully';
} catch (Exception $exception) {
echo 'Error: ' . $exception->getMessage();
}
$connection->close();
?>
</html>