What are the potential security risks associated with 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 input to execute unauthorized SQL commands. To prevent this, you should always use prepared statements with parameterized queries to securely handle user input.

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

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

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

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

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

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