Tags
PHP
Asked 2 years ago
18 May 2021
Views 795
sarah

sarah posted

how to use mysqli_num_rows in php ?

is the mysqli_num_rows used as mysql_num_rows ?

jqueryLearner

jqueryLearner
answered Nov 30 '-1 00:00

if you don't want to use mysqli_num_rows than you can count the rows at Mysql Queries as well

$selectquery="select count(*) as c from `tablename`";
    $results = mysqli_query($conn, $selectquery); 
      
    if ($resultset) 
    { 
         $data = mysqli_fetch_rows($results); 
echo $data['c'];
}

it will print the total count of the rows for Mysql Query
sandip

sandip
answered Nov 30 '-1 00:00

mysqli_num_rows take parameter as result which can be get by function like mysqli_query(), mysqli_store_result() or mysqli_use_result()
mysqli_num_rows function return value total number of record for that particular query.

$result =mysqli_query($connection,"Your query goes here");
$totalrecord=mysqli_num_rows(result);


$totalrecord have integer value of the total number record of the given sql query.
noob

noob
answered Nov 30 '-1 00:00

complete code for getting number of rows from resulset
connect with mysql database with php

suppose you have database username : "admin" and database passwoord : "admin" and database name is "newdata"

   $dbconn = mysqli_connect("localhost", "admin", "admin",  "newdata"); 


after the established connection to the database
and now run the query and generate the resultset

    $sqlquery = "SELECT * from users"; 
     $resultset = mysqli_query($dbconn, $sqlquery); 


if resultset is generated ok than fetch the data or get the number of the rows by mysqli_num_rows with resultset.

    if ($resultset) 
    { 
        //mysqli_num_rows return number of rows in the table. 
        $totalrows = mysqli_num_rows($resultset); 
}


Final code will be like :

<?php 
 
   $dbconn = mysqli_connect("localhost", "admin", "admin",  "newdata"); 
      
 
    if (mysqli_connect_errno()) 
    { 
        echo "Database connection failed."; 
    } 
      
 //prepare query
    $sqlquery = "SELECT * from users"; 
      
    // run the query and generate results
    $resultset = mysqli_query($dbconn, $sqlquery); 
      
    if ($resultset) 
    { 
        //mysqli_num_rows return number of rows in the table. 
        $totalrows = mysqli_num_rows($resultset); 
         echo "Total records :".$totalrows;
    
        // release the result set. 
        mysqli_free_result($resultset); 
    } 
  
    // Connection close  
    mysqli_close($dbconn); 
?> 


it is very good if you close connection by mysqli_close and also free the resultset mysqli_free_result($resultset) for better performance.
david

david
answered Nov 30 '-1 00:00

you can use mysqli_fetch_array or mysqli_fetch_row or mysqli_fetch_object to get the number of the rows

        $totalrecords = count(mysqli_fetch_array($resultset)); 
echo $totalrecords;

it will print total records for the given resultset
Post Answer