How can the coalesce function be effectively used in SQL queries to handle null values in PHP?
When working with SQL queries in PHP, the COALESCE function can be used to handle null values effectively. This function returns the first non-null expression among its arguments. By using COALESCE, you can replace null values with a default value or another column's value in your query results.
// Example SQL query using COALESCE to handle null values
$query = "SELECT id, name, COALESCE(age, 0) AS age FROM users";
$result = mysqli_query($connection, $query);
if(mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "ID: " . $row['id'] . ", Name: " . $row['name'] . ", Age: " . $row['age'] . "<br>";
}
} else {
echo "No results found.";
}