What are the best practices for handling user input data in PHP to prevent SQL injection attacks?

To prevent SQL injection attacks in PHP, it is important to always sanitize and validate user input data before using it in SQL queries. One common method to achieve this is by using prepared statements with parameterized queries, which separate the SQL query logic from the user input data. By binding parameters to placeholders in the query, the database engine can distinguish between the query and the user input, effectively preventing SQL injection attacks.

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

// Sanitize and validate user input data
$userInput = $_POST['user_input'];
$userInput = filter_var($userInput, FILTER_SANITIZE_STRING);

// Prepare a SQL query using a parameterized statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the sanitized user input to the query parameter
$stmt->bindParam(':username', $userInput);

// Execute the query
$stmt->execute();

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