What potential security risks are associated with including variables in SQL queries in PHP?

When including variables in SQL queries in PHP, there is a risk of SQL injection attacks if the variables are not properly sanitized. To mitigate this risk, it is important to use prepared statements with parameterized queries. This helps prevent malicious SQL code from being injected into the query.

// Using prepared statements to prevent SQL injection

// Assuming $conn is the database connection

// Prepare a SQL query with a placeholder for the variable
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");

// Bind the variable to the placeholder
$stmt->bind_param("s", $username);

// Set the variable value
$username = "example_user";

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

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

// Process the results
while ($row = $result->fetch_assoc()) {
    // Handle the data
}

// Close the statement
$stmt->close();