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

Directly inserting user input into SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the query to access or modify sensitive data in the database. To prevent this, it is important to use prepared statements with parameterized queries, which separate the SQL code from the user input, preventing any malicious commands from being executed.

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

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

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

// Bind the user input to the parameter
$stmt->bindParam(':username', $userInput);

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

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