What are the potential security risks of directly inserting variables into SQL code in PHP?

Directly inserting variables into SQL code in PHP can lead to SQL injection attacks, where malicious users can manipulate the SQL query to execute unauthorized commands on the database. To prevent this, you should always use prepared statements with parameterized queries in PHP when interacting with a database. This way, the input values are treated as data rather than executable code, making it much harder for attackers to inject malicious SQL commands.

// Using prepared statements with parameterized queries to prevent SQL injection
$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();

$result = $stmt->fetch();