What potential security risks are involved in directly outputting SQL query results in PHP without proper sanitization or validation?
Outputting SQL query results in PHP without proper sanitization or validation can lead to SQL injection attacks, where malicious SQL code is injected into the query, potentially allowing attackers to access or manipulate the database. To prevent this, it is important to sanitize and validate the data before outputting it to ensure that it does not contain any harmful code.
// Example of sanitizing and validating SQL query results before outputting
$query = "SELECT * FROM users WHERE id = " . $id;
$result = mysqli_query($connection, $query);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
$username = htmlspecialchars($row['username']); // Sanitize the data before outputting
echo "Username: " . $username . "<br>";
}
} else {
echo "Error executing query: " . mysqli_error($connection);
}