What are the potential security risks associated with not properly sanitizing SQL queries in PHP?

Failure to properly sanitize SQL queries in PHP can lead to SQL injection attacks, where malicious users can manipulate the database by injecting their own SQL code. This can result in unauthorized access to sensitive data, data loss, or even complete database compromise. To prevent this, it is important to use parameterized queries or prepared statements to sanitize user input before executing SQL queries.

// Example of using prepared statements to sanitize SQL queries in PHP
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Sanitize user input
$user_input = $_POST['user_input'];

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

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

// Use the results as needed
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}