What potential security risks are present when querying a database without proper escaping in PHP?

When querying a database without proper escaping in PHP, there is a risk of SQL injection attacks. This occurs when a user input is directly included in a SQL query without sanitization, allowing malicious users to manipulate the query and potentially access or modify sensitive data in the database. To mitigate this risk, it is essential to use parameterized queries or prepared statements with placeholders for user input. This method separates the SQL query logic from the user input, preventing any malicious SQL code from being executed.

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

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

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

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

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