gpt4 book ai didi

php - 尝试从表单将数据插入数据库时​​出现错误

转载 作者:行者123 更新时间:2023-11-29 16:30:33 25 4
gpt4 key购买 nike

我正在尝试使用 HTML 表单将数据插入到我的数据库中。用随机数据填充输入字段后,我总是遇到相同的错误:

Error: INSERT INTO employee (id, email, passwort, vorname, nachname, created_at, updated_at) VALUES (NULL, hhh@yahoo.com, hfjfhf, , ffffff, 2018-06-12, 2018-11-11)
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '@yahoo.com, hfjfhf, , ffffff, 2018-06-12, 2018-11-11)' at line 2

ID 字段设置为自动递增,我尝试将其从“INSERT INTO”SQL 命令中删除,但每次都会出现相同的错误。

这是我的代码:

<html>
<head>
<title>Create new user</title>
</head>
<body>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Name: <input type="text" name="name"><br>
Lastname: <input type="text" name="lastname"><br>
E-mail: <input type="email" name="email"><br>
Password: <input type="password" name="password1"><br>
Creation Date: <input type="text" name="cdate"><br>
Update Date: <input type="text" name="udate"><br>
<input type="submit" value"Send">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "users";
$email = $_POST["email"];
$name = $_POST["name"];
$surname = $_POST["lastname"];
$password1 = $_POST["password1"];
$cdate = $_POST["cdate"];
$udate = $_POST["udate"];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO employee (id, email, passwort, vorname, nachname, created_at, updated_at)
VALUES (NULL, $email, $name, $surname, $password1, $cdate, $udate)";

if ($conn->query($sql) === TRUE) {
echo "record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
</div>
</body>
</html>

最佳答案

您需要在查询中的字符串周围加上引号:

$sql = "INSERT INTO employee (email, passwort, vorname, nachname, created_at, updated_at)
VALUES ('$email', '$name', '$surname', '$password1', '$cdate', '$udate')";

此外,我没有在 INSERT 语句中包含自动递增字段的值,因为您的数据库引擎会自动处理该问题,不要像您那样尝试将其设置为 NULL在你的代码中做了。

我建议出于安全目的转义您的数据(主要是 SQL 注入(inject))。您可以阅读更多here .

但是,您可能希望转义表单输入数据的方式如下:

$conn = new mysqli($servername, $username, $password, $dbname);

$email = mysqli_real_escape_string($conn, $_POST["email"]);
$name = mysqli_real_escape_string($conn, $_POST["name"]);
$surname = mysqli_real_escape_string($conn, $_POST["lastname"]);
$password1 = mysqli_real_escape_string($conn, $_POST["password1"]);
$cdate = mysqli_real_escape_string($conn, $_POST["cdate"]);
$udate = mysqli_real_escape_string($conn, $_POST["udate"]);

关于php - 尝试从表单将数据插入数据库时​​出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53958772/

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