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

时间:2018-12-28 12:38:51

标签: php mysql

我正在尝试使用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>

1 个答案:

答案 0 :(得分:0)

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

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

此外,我没有在INSERT语句中包括auto-incremented字段的值,因为您的数据库引擎将自动处理该问题,请勿像在您的示例中那样将其设置为NULL代码。

我建议出于安全目的(主要是SQL注入)转义数据。您可以阅读更多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"]);