What are the security risks associated with not escaping variables in SQL queries in PHP?

When variables are not escaped in SQL queries in PHP, it opens up the possibility of SQL injection attacks where an attacker can manipulate the query to execute unauthorized SQL commands. To prevent this, it is crucial to escape variables using prepared statements or parameterized queries in PHP.

// Using prepared statements to escape variables in SQL queries
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();