当我单击提交按钮而不填写表单时,数据库中会出现一个新条目,但该表格会继续验证并向用户显示,此字段是必填项,但表单仍在提交给数据库?
这是我的代码,请帮助,我是PHP的新手,并且非常厌倦解决这样的问题。
<?php
include 'dbc.php';
// define variables and set to empty values
$name_error = $email_error = $phone_error = $url_error = $message_error = "";
$name = $email = $phone = $message = $url = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
}
if (empty($_POST["url"])) {
$url_error = "Website url is required";
} else {
$url = test_input($_POST["url"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$url)) {
$url_error = "Invalid URL";
}
}
if (empty($_POST["message"])) {
$message_error = "Message field is required";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
$message = 'Hello Ladies';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message .= "$key: $value\n";
}
$to = 'sample@email.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message)){
$success = "Message sent, thank you for contacting us!";
}
}
$query = "INSERT INTO clients(name,email,phone,url,message) ";
$query .= "VALUES('$name', '$email', '$phone', '$url', '$message') ";
$create_user = mysqli_query($mysqli, $query);
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
我希望我不会失败。
答案 0 :(得分:0)
在查询运行之前实际进行的唯一检查是
if ($_SERVER["REQUEST_METHOD"] == "POST") {
这意味着插入值的唯一要求是表单是通过POST发送的,没有别的。这可以使用适当的编辑器进行检查,并查看查询周围的括号。您在代码中先前进行了一些检查以验证和检查输入,但这并不能说明是否应该运行查询。
如果移动以下if-block
的右括号}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $url_error == '' and $message_error == ''){
在执行查询后,只有在通过所有检查后才会运行查询。 (将它放在以下代码段之后)
if (!$create_user) {
die("QUERY FAILED. " . mysqli_error($mysqli));
}
在其他评论中,您的test_input()
是垃圾(真的),您不应该使用它。改为参数化您的查询并使用适当的函数过滤输入。已经在PHP中实现了validation filters和sanitation filters,如果需要,您应该使用它们。
您应该使用mysqli::prepare()
准备和绑定查询的值,这将处理与引号有关的任何问题并保护您的数据库免受SQL注入。