What potential issues can arise when using variables directly in SQL queries in PHP?

Using variables directly in SQL queries in PHP can lead to SQL injection attacks, where malicious code is injected into the query, potentially compromising the security of the database. To prevent this, it is recommended to use prepared statements with parameterized queries, which separate the SQL query from the user input.

// Using prepared statements to prevent SQL injection

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

// Prepare a SQL query with a placeholder for the variable
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the variable to the placeholder
$stmt->bindParam(':username', $username);

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

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