How does the mysqli_num_rows() function help in resolving the problem?
The issue is that we need to check the number of rows returned by a query in MySQL using PHP. This is important for tasks like verifying if a user exists in a database or if a search query returned any results. The mysqli_num_rows() function helps us to easily get the number of rows returned by a query, allowing us to make decisions based on that information.
// Establish a connection to the database
$conn = mysqli_connect("localhost", "username", "password", "database");
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a query
$result = mysqli_query($conn, "SELECT * FROM users");
// Check the number of rows returned by the query
if (mysqli_num_rows($result) > 0) {
// Rows exist, do something
echo "Rows found!";
} else {
// No rows returned
echo "No rows found.";
}
// Close the connection
mysqli_close($conn);