我创建了一个简单的 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(); } ?>
最佳答案
试试这个:
<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>
关于php - 从登录页面将数据提交到 MySQL 数据库的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56911448/