What are the potential security risks associated with using user input directly in SQL queries in PHP?

Using user input directly in SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the input to execute unintended SQL commands. To prevent this, it is important to sanitize and validate user input before using it in SQL queries. One way to do this is by using prepared statements and parameterized queries, which separate the SQL code from the user input, making it impossible for attackers to inject malicious code.

// Using prepared statements to prevent SQL injection

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

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

// Bind the user input to the placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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