要将PHP操作与HTML表单关联,您需要执行以下几个步骤:
action
属性,该属性指向处理表单数据的PHP文件。method
属性,以指定HTTP请求方法(通常为POST
或GET
)。这是一个简单的示例,说明如何将HTML表单与PHP操作关联:
HTML表单 (form.html):
<!DOCTYPE html>
<html>
<head>
<title>Form Example</title>
</head>
<body>
<h1>Simple Form</h1>
<form action="process_form.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP操作 (process_form.php):
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'];
$email = $_POST['email'];
// Perform actions with the form data, e.g., save to database, send email, etc.
echo "Name: " . htmlspecialchars($name) . "<br>";
echo "Email: " . htmlspecialchars($email) . "<br>";
}
?>
在此示例中,当用户填写表单并点击“提交”按钮时,表单数据将发送到process_form.php
文件。在该文件中,我们通过$_POST
变量获取表单数据,并对其进行处理。