尝试用php将用户输入保存到mysql时出错

ee7vknir  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(331)

每当我尝试将用户输入保存到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>

如果我做错了什么,请告诉我。谢谢

htrmnn0y

htrmnn0y1#

请参见下面的修改代码:

$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>
yr9zkbsy

yr9zkbsy2#

<?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";
 }

}
?>

请试试这个

相关问题