尝试从窗体向数据库中插入数据时出错

3bygqnnd  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(400)

这个问题在这里已经有答案了

在mysql中何时使用单引号、双引号和反引号(13个答案)
两年前关门了。
我正在尝试使用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>
nfg76nw0

nfg76nw01#

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

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

此外,我没有在insert语句中包含自动递增字段的值,因为db引擎会自动处理这个问题,不要尝试将其设置为 NULL 就像你在代码里做的那样。
我建议出于安全目的转义数据(主要是sql注入)。你可以在这里读更多。
但是,以下是您可能希望如何转义表单输入数据:

$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"]);

相关问题