What common mistakes can occur when handling form data in PHP, as seen in the provided code snippet?
One common mistake when handling form data in PHP is not properly sanitizing user input, leaving the application vulnerable to SQL injection attacks. To solve this issue, always sanitize and validate user input before using it in SQL queries or displaying it on the page.
// Sanitize and validate user input before using it
$username = filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
// Display appropriate error message if login fails
if($stmt->rowCount() > 0){
echo "Login successful!";
} else {
echo "Invalid username or password.";
}
Keywords
Related Questions
- What are the potential pitfalls of using query parameters to control the number of entries displayed per page in PHP?
- Are there any best practices for efficiently querying and displaying data from multiple tables in PHP?
- How can error reporting functions like error_reporting(E_ALL) and ini_set('display_errors', true) help troubleshoot PHP code?