What potential security risks are associated with directly inserting user input into a database query in PHP?

Directly inserting user input into a database query in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access or modify sensitive data. To prevent this, you should always use prepared statements with parameterized queries to sanitize and validate user input before executing the query.

// Using prepared statements to prevent SQL injection
$pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");

// User input
$userInput = $_POST['user_input'];

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

// Bind parameters
$stmt->bindParam(':username', $userInput);

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

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

// Process the results
foreach ($results as $row) {
    // Process each row
}