每当我尝试将用户输入保存到MySQL数据库时,只要我加载页面就会保存空行。这是我的index.php文件:
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$uName = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['username']);
$pass = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['password']);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (username, password)
VALUES ('$uName', '$pass')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<body>
<form action="index.php" method="post">
<input type="text" name="username"> <br> <br>
<input type="password" name="password"> <br> <br>
<input type="submit" name="submit">
</form>
</body>
</html>
请告诉我是否有任何错误。 感谢
答案 0 :(得分:0)
请参阅以下修改后的代码:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit'])){
$uName = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['username']);
$pass = mysqli_real_escape_string(mysqli_connect($servername, $username,
$password, $dbname), $_POST['password']);
$sql = "INSERT INTO users (username, password)
VALUES ('$uName', '$pass')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="" method="post">
<input type="text" name="username"> <br> <br>
<input type="password" name="password"> <br> <br>
<input type="submit" name="submit">
</form>
</body>
</html>
答案 1 :(得分:0)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['submit']))
{
$uName=$_POST['username'];
$password=$_POST['password'];
$sql = "INSERT INTO users (username, password) VALUES ('$uName', '$pass')";
if(mysqli_query($conn, $sql)){
{
echo "New record inserted successfully";
}
else
{
echo "There have some problem";
}
}
?>
请试试这个