How can developers avoid errors like "Trying to get property 'num_rows' of non-object" when querying databases in PHP?
To avoid errors like "Trying to get property 'num_rows' of non-object" when querying databases in PHP, developers should check if the query was successful before trying to access properties like 'num_rows'. This can be done by verifying if the query returned a valid result object before attempting to access its properties.
// Perform a database query
$query = $mysqli->query("SELECT * FROM table");
// Check if the query was successful
if ($query) {
// Access the 'num_rows' property only if the query was successful
$num_rows = $query->num_rows;
// Process the query results
while ($row = $query->fetch_assoc()) {
// Do something with the data
}
} else {
// Handle the case where the query was not successful
echo "Error executing query: " . $mysqli->error;
}
Related Questions
- How can array_shift() be used to retrieve the first element of an array in PHP when including multiple pages?
- How can the code provided in the forum thread be optimized for better performance and security when exchanging data between domains in PHP?
- What are some common mistakes to avoid when passing variables with cURL in PHP?