What are some alternative methods to using the mysql_num_rows function in PHP for performance optimization when querying a database?

Using the mysql_num_rows function in PHP to count the number of rows returned by a query can be inefficient for large result sets as it requires fetching all rows from the database. To optimize performance, you can use the SQL COUNT() function to directly get the count of rows without fetching the actual data. This can significantly reduce the load on the database server and improve the overall performance of your application.

// Connect to the database
$conn = mysqli_connect("localhost", "username", "password", "database");

// Query to get the count of rows
$query = "SELECT COUNT(*) as count FROM table_name";
$result = mysqli_query($conn, $query);

// Fetch the count
$row = mysqli_fetch_assoc($result);
$count = $row['count'];

// Output the count
echo "Total rows: " . $count;

// Close the connection
mysqli_close($conn);