Are there best practices to follow when using JOIN in PHP to avoid errors like "Trying to get property of non-object"?

When using JOIN in PHP to retrieve data from a database, it is essential to check if the query was successful and if the result set contains any rows before trying to access properties of the returned object. This error typically occurs when trying to access properties of a null object, which happens when the query fails or returns no results.

// Perform a JOIN query to retrieve data
$query = "SELECT * FROM table1 JOIN table2 ON table1.id = table2.table1_id";
$result = mysqli_query($connection, $query);

// Check if the query was successful and if there are any rows returned
if ($result && mysqli_num_rows($result) > 0) {
    // Fetch the data as an associative array
    while ($row = mysqli_fetch_assoc($result)) {
        // Access properties of the $row array
        echo $row['column_name'];
    }
} else {
    echo "No results found.";
}