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
- Are there any best practices for integrating error logging tools like Hoptoad/Airbrake in PHP scripts?
- What potential issue is indicated by the error message "Notice: Undefined offset: 3" in the code?
- In PHP, how can you remove all whitespace characters except spaces from a string using regular expressions?