What are the best practices for handling form data from $_POST in PHP to prevent SQL injection vulnerabilities?

To prevent SQL injection vulnerabilities when handling form data from $_POST in PHP, it is important to use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input data, making it impossible for malicious input to interfere with the query execution.

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

// Prepare a SQL statement using a parameterized query
$stmt = $pdo->prepare("INSERT INTO users (username, email) VALUES (:username, :email)");

// Bind the parameters with the actual form data values
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':email', $_POST['email']);

// Execute the prepared statement
$stmt->execute();