How can the code snippet be optimized to reduce redundancy and improve readability by combining the calculation of 'erreichbarkeit' directly in the SQL query?
The issue can be solved by combining the calculation of 'erreichbarkeit' directly in the SQL query using a CASE statement. This will reduce redundancy by eliminating the need for separate calculations in the PHP code and improve readability by keeping the logic within the query itself.
$sql = "SELECT *,
CASE
WHEN (standort = 'Berlin' AND entfernung <= 50) THEN 'erreichbar'
WHEN (standort = 'München' AND entfernung <= 100) THEN 'erreichbar'
ELSE 'nicht erreichbar'
END AS erreichbarkeit
FROM standorte";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Standort: " . $row["standort"]. " - Entfernung: " . $row["entfernung"]. " - Erreichbarkeit: " . $row["erreichbarkeit"]. "<br>";
}
} else {
echo "0 results";
}