How should the result of a MySQL query be handled and returned in a PHP function to avoid errors like "null given"?
When executing a MySQL query in PHP, the result should be checked for errors and handled properly to avoid issues like "null given." To prevent this error, you can check if the query was successful and if it returned any rows before attempting to fetch the data. This can be done by using functions like mysqli_num_rows() to check the number of rows returned by the query.
function fetchDataFromDatabase($connection) {
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
if ($result) {
if (mysqli_num_rows($result) > 0) {
$data = mysqli_fetch_assoc($result);
return $data;
} else {
return "No data found";
}
} else {
return "Error executing query: " . mysqli_error($connection);
}
}