29

What is the best MySQL command to count the total number of rows in a table without any conditions applied to it? I'm doing this through php, so maybe there is a php function which does this for me? I don't know. Here is an example of my php:

<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("some command");
$row = mysql_fetch_array($result);

mysql_close($con);
?>
0

12 Answers 12

57
<?php
$con = mysql_connect("server.com","user","pswd");
if (!$con) {
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("db", $con);

$result = mysql_query("select count(1) FROM table");
$row = mysql_fetch_array($result);

$total = $row[0];
echo "Total rows: " . $total;

mysql_close($con);
?>
Sign up to request clarification or add additional context in comments.

3 Comments

What about in PHP 5.3?
it don't work true with LIMIT in query - this method return real count of array
**2022: STOP USING MYSQL METHODS, THESE ARE NOT SECURE AND REMOVED FROM PHP! Use MySQLi or PDO instead.
27

Either use COUNT in your MySQL query or do a SELECT * FROM table and do:

$result = mysql_query("SELECT * FROM table");
$rows = mysql_num_rows($result);
echo "There are " . $rows . " rows in my table.";

3 Comments

You're first part is correct. I would emit the last part pulling back the entire dataset. In this questions scope, that's a waste of resources for a simple count.
@George I would not suggest using it either. But as he asked if there was any PHP function that could do it, I just shared the option. Just answering the question.
And that's fine, however, it's always good to point out potential issues like this when you answer a question. Not only does it help the user understand the differences, it increases the legitimacy of your answer, and the attention it gets. Which means, more points for you! :)
9

mysqli_num_rows is used in php 5 and above.

e.g

<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  printf("Result set has %d rows.\n",$rowcount);
  // Free result set
  mysqli_free_result($result);
  }
mysqli_close($con);
?>

Comments

6

Use COUNT in a SELECT query.

$result = mysql_query('SELECT COUNT(1) FROM table');
$num_rows = mysql_result($result, 0, 0);

1 Comment

Use mysql_result (the best for this instance, IMHO) or one of the similar functions for fetching data from result sets.
6

you can do it only in one line as below:

$cnt = mysqli_num_rows(mysql_query("SELECT COUNT(1) FROM TABLE"));
echo $cnt;

5 Comments

Why are you writing this answer, when there's accepted answer? And this question has been asked in 2011.
...using a deprecated library (mysql). use mysqli instead
that is a horrible answer, sending the entire table across to count rows?
use the select count(1) from table to get the count and put into a variable
This answer is wrong. It return always 1 because you count the amount of records returned from the query. Since that you are using an aggregate function like COUNT you will get always an row in the result, and later you count this row thereby you'll get always 1. Furthermore you are using a deprecated library
4

use num_rows to get correct count for queries with conditions

$result = $connect->query("select * from table where id='$iid'");
$count=$result->num_rows;
echo "$count";

1 Comment

Good but what is where id='$iid'?!!!!!!!
2

for PHP 5.3 using PDO

<?php
    $staff=$dbh->prepare("SELECT count(*) FROM staff_login");
    $staff->execute();
    $staffrow = $staff->fetch(PDO::FETCH_NUM);
    $staffcount = $staffrow[0];


    echo $staffcount;
?>

1 Comment

Good addition. A small enhancement: If you use $staffcount = $staff->fetchColumn(); you can get rid of the $staffrow temporary variable.
2
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";

if ($result=mysqli_query($con,$sql))
  {
  // Return the number of rows in result set
  $rowcount=mysqli_num_rows($result);
  echo "number of rows: ",$rowcount;
  // Free result set
  mysqli_free_result($result);
  }

mysqli_close($con);
?>

it is best way (I think) to get the number of special row in mysql with php.

1 Comment

This technique has already been answered. Why "special rows"? They are just query result rows.
1
<?php
$conn=mysqli_connect("127.0.0.1:3306","root","","admin");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="select count('user_id') from login_user";
$result=mysqli_query($conn,$sql);
$row=mysqli_fetch_array($result);
echo "$row[0]";
mysqli_close($conn);
?>

Still having problem visit my tutorial http://www.studentstutorial.com/php/php-count-rows.php

Comments

0
$sql = "select count(column_name) as count from table";

Comments

0

It`s better to count rows directly in the database, it is more efficient for large tables.

$tableName = 'my-table'
$sql = "SELECT COUNT(*) FROM $tableName";
$row = mysqli_fetch_assoc(mysqli_query($conn, $sql));
$row_count = $row['COUNT(*)'];

Comments

-1

Well, I used the following approach to do the same: I have to get a count of many tables for listing the number of services, projects, etc on the dashboard. I hope it helps.

PHP Code

// create a function 'cnt' which accepts '$tableName' as the parameter.

 function cnt($tableName){
        global $conection;
        $itemCount = mysqli_num_rows(mysqli_query($conection, "SELECT * FROM `$tableName`"));
        echo'<h6>'.$itemCount.'</h6>';
    }

Then when I need to get the count of items in the table, I call the function like following

<?php
  cnt($tableName = 'projects');
?>

In my HTML front end, so it renders the count number

  • It's to be noted that I create the cnt() function as a global function in a separate file which I include in my head, so I can call it from anywhere in my code.

2 Comments

It is very less optimize than the COUNT(*) approach
Well it can be but I can't get it working while this worked for me, so no issues.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.