What are the potential security risks associated with querying a database using user input in PHP?

When querying a database using user input in PHP, there is a risk of SQL injection attacks where malicious users can input SQL commands to manipulate the database. To prevent this, it is important to sanitize and validate user input before using it in a database query. This can be done by using prepared statements or parameterized queries to ensure that user input is treated as data rather than executable code.

// Sanitize and validate user input before using it in a database query
$user_input = $_POST['user_input'];

// Prepare a SQL statement using a prepared statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->bindParam(':username', $user_input, PDO::PARAM_STR);
$stmt->execute();

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