混合php和html文件

joh*_*ble 2 html php

现在我有2个文件,一个php文件和一个html文件,我想制作一个表格.在我的html文件中,我有网站的内容以及我的表格.在我的php文件(名为contact.php)中,我试图处理php中的输入.现在当我点击提交时,html表单将我带到我的php文件并且不回显输入.我知道我可以把所有的html和php都放到一个php文件中,这样可以工作,但是有什么方法可以用我现在拥有的东西.

HTML代码

<form action = "contact.php" method = "POST">
name: <input type = "text" name = "name"> <br>
email: <input type = "text" name = "email"> <br>
subject: <input type = "text" name = "subject"> <br>
<input type = "submit" value = "submit" name = "submit"> <br>
</form>
Run Code Online (Sandbox Code Playgroud)

PHP代码

 <?php 
$name = "";
$email = "";
$subject = "";
$nameError = "";
$emailError = "";
$subjectError = "";
$x = 5;
function filterData($data)  {
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
$connection = mysqli_connect('x', 'x', 'x'); 
if (!connection) { 
    die('Could not connect: ' . mysqli_error()); 
} 

mysqli_select_db(contact); 

if ($_SERVER["REQUEST_METHOD"] == "POST") {
//handles the name 
if (empty($name)) {
$nameError = "please don't leave the name field blank";
}
else {
$name = filterData($_POST["name"]);
}
//handles the email
if (empty($email)) {
$emailError = "please don't leave the email field blank";
}
else {
$email = filterData($_POST["email"]);
}
//handles the subject
if (empty($subject)) {
$subjectError = "please don't leave this field blank";
}
else {
$subject = filterData($_POST["subject"]);
}

}

echo $name;
echo $subject;
echo $email;



?> 
Run Code Online (Sandbox Code Playgroud)

Chr*_*ear 5

empty太早做了检查.

更改

if (empty($name)) {
    $nameError = "please don't leave the name field blank";
}
else {
    $name = filterData($_POST["name"]);
}
Run Code Online (Sandbox Code Playgroud)

$name = filterData($_POST["name"]);
if (empty($name)) {
    $nameError = "please don't leave the name field blank";
}
Run Code Online (Sandbox Code Playgroud)

对其他变量定义进行类似的更改.

你也可以呼应$nameError,$emailError$subjectError看到一个好一点发生了什么事情.