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

To prevent SQL injection attacks in PHP, it is important to sanitize and validate user inputs before using them in SQL queries. This can be done by using prepared statements with parameterized queries, using PDO or MySQLi extensions, and escaping special characters. Additionally, implementing input validation and limiting user privileges can further enhance security.

// Example of using prepared statements with PDO to prevent SQL injection

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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