What are the potential security risks of inserting values directly into SQL queries in PHP?

Inserting values directly into SQL queries in PHP can make your application vulnerable to SQL injection attacks. To prevent this, you should always use prepared statements with parameterized queries. This way, user input is treated as data rather than executable code, reducing the risk of SQL injection.

// Using prepared statements 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();

// Fetching results
$results = $stmt->fetchAll();