DEV Community

Lalit Kumar
Lalit Kumar

Posted on

Mysqli_num_rows in PHP

PHP is an open-source programming language; it has built-in functions to communicate with the database and retrieve data. Mysqli_num_rows () function is used to check the number of rows in the query. This function is used after placing a query to check either database has any record or it is empty. This function has a return value. It returns the number of rows a table contains if the condition comes true and returns false for empty tables.

How to use Mysqli_num_rows ()?

To use this function, you need to establish a database connection. this function returns true if the database has any record and returns false if the database has an empty recordset. This function is used to avoid errors in a web application because without checking the recordset if we perform further actions a program may have fatal errors and exceptions.

Syntax of mysqli_num_rows function

mysqli_num_rows(result)

To check either if a database contains any rows, we need to pass a parameter or variable, variable contains the result returned by mysql_query. It checks a database and if there is any record it will return true and if there is nothing it will return false or empty.

Example: let’s explore and evaluate this with the help of an example.

<?php
$connection=mysqli_connect("localhost","username","password","database");
// Check connection
if (mysqli_connect_errno())
  {
  echo "database connection failed: " . mysqli_connect_error();
  }

$sql="SELECT Name,Lastname,Age,Class FROM students ORDER BY Lastname";

if ($result=mysqli_query($connection,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);//check if the database has any record
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($connection);
?>
Enter fullscreen mode Exit fullscreen mode

title: "originally posted here πŸ‘‡"

canonical_url: https://kodlogs.com/blog/2538/mysqli_num_rows-in-php

code explained:

  1. first, we made a connection to the database and checked if the connection is valid
  2. note that PHP is case sensitive for database records field names so always use the same as in tables
  3. we used a variable $sql and assign a query to it
  4. we check if the query is valid and assigned it to the $result variable
  5. we used $rowscount and passed it the value of mysqli_num_rows
  6. mysqli_num_rows will check the database and returns either try or false Read more in original post

Top comments (0)