How to Determine Which Tech Area to Focus on as a Beginner
Tech in Education |
2025-02-21 12:33:15
Creating a form in PHP involves two parts:
This form contains input fields and a submit button.
<form action="process.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<input type="submit" value="Submit">
</form>
action="process.php"
→ Sends form data to process.php
for processing.method="post"
→ Uses the POST method to send data securely.Create process.php
to handle the submitted data.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
}
?>
$_SERVER["REQUEST_METHOD"] == "POST"
→ Ensures the form is submitted using POST.$_POST['name']
→ Retrieves the form data.htmlspecialchars()
→ Prevents XSS attacks by escaping special characters.To validate inputs before processing:
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (!empty($_POST['name']) && filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
echo "Valid Submission!<br>";
echo "Name: " . $name . "<br>";
echo "Email: " . $email;
} else {
echo "Invalid input. Please check your details.";
}
}
?>
!empty($_POST['name'])
→ Ensures the name field is not empty.filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
→ Validates email format.If you want to store the submitted data in a MySQL database:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test_db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully!";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
mysqli
is used to connect to the MySQL database.real_escape_string()
prevents SQL injection.Would you like to add a file upload field or other custom features? 🚀