What are best practices for processing form data in PHP scripts to insert into a database?
When processing form data in PHP scripts to insert into a database, it is important to sanitize and validate the input to prevent SQL injection and other security vulnerabilities. One common practice is to use prepared statements with parameterized queries to safely insert data into the database.
// Assuming you have already established a database connection
// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
// Prepare and execute a SQL query using prepared statements
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (:name, :email)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->execute();