What are some best practices for handling user input data from forms in PHP to prevent SQL injection?

To prevent SQL injection when handling user input data from forms in PHP, it is essential to sanitize and validate the input before using it in SQL queries. One way to achieve this is by using prepared statements with parameterized queries, which separate the SQL code from the user input data. This helps prevent malicious SQL code from being injected into the query.

// Establish a database connection
$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");

// Sanitize and validate user input
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Process the results as needed