How can user data be securely passed to a PHP file for database queries?

User data can be securely passed to a PHP file for database queries by using prepared statements with parameterized queries. This helps prevent SQL injection attacks by separating the SQL query from the user input data. By binding parameters to placeholders in the query, the database can distinguish between the query structure and the user input, ensuring that the data is treated as data and not as part of the query.

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

// Prepare a SQL query 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(PDO::FETCH_ASSOC);

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . "<br>";
}