What are some best practices for developing a PHP form to input and display data on a website?
When developing a PHP form to input and display data on a website, it is important to sanitize user input to prevent SQL injection attacks and validate input to ensure data integrity. Additionally, using prepared statements when interacting with a database can help prevent SQL injection vulnerabilities. Lastly, consider implementing client-side validation using JavaScript to provide immediate feedback to users.
<?php
// Sanitize user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Validate input
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "Invalid email format";
}
// Prepare and execute SQL statement
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':email', $email);
$stmt->execute();
?>
Related Questions
- What potential pitfalls can arise from using undefined functions like setrange() in PHP code?
- How can PHP developers ensure that the link text is not lost when using regular expressions to modify forum tags?
- What are some best practices for integrating HTML code within PHP to achieve desired output?