What are the best practices for handling user input in PHP to prevent SQL injection vulnerabilities in a forum application?

To prevent SQL injection vulnerabilities in a forum application, it is important to properly sanitize and validate user input before using it in database queries. One way to achieve this is by using prepared statements with parameterized queries in PHP. This helps to separate the SQL code from the user input, making it impossible for malicious input to alter the SQL query.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM posts WHERE id = :id");

// Bind the user input to the parameter
$stmt->bindParam(':id', $_GET['post_id']);

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

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