gpt4 book ai didi

php - 尝试使用 PHP 将用户输入保存到 MySQL 时出错

转载 作者:行者123 更新时间:2023-11-29 17:34:27 25 4
gpt4 key购买 nike

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

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

最佳答案

请参阅下面修改后的代码:

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

关于php - 尝试使用 PHP 将用户输入保存到 MySQL 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50404888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com