How can PHP code be structured to handle form submission and database insertion effectively?
To handle form submission and database insertion effectively in PHP, you can structure your code by first checking if the form has been submitted, then validating the form data, and finally inserting the data into the database. Make sure to use prepared statements to prevent SQL injection attacks.
<?php
// Check if the form has been submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate form data
$name = $_POST['name'];
$email = $_POST['email'];
// Insert data into the database using prepared statements
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();
// Redirect to a success page
header("Location: success.php");
exit();
}
?>
Related Questions
- In the context of PHP, what are some best practices for structuring MySQL queries to handle situations where data needs to be consolidated into a single row from multiple tables?
- Are there any best practices for handling timestamps in PHP to ensure accuracy and efficiency?
- What is a best practice for handling empty query results in PHP?