Sheikhasa Mozali
Sheikhasa Mozali

Reputation: 237

count the number of rows in mysql?

How to count the number of rows in mysql database tables with php?

if have in database 5 rows, they number show like this(bold):

all columns is: 5

1 row1
2 row2
3 row3
4 row4
5 row5

Upvotes: 0

Views: 4001

Answers (4)

Aniket
Aniket

Reputation: 9758

You can use this

$result = $this->db->get(<table_name>);
$num_rows = $result->num_rows();

$num_rows would be the total rows in table_name

Then you can just do this

echo 'The number of rows in table_name is '.$num_rows;

Upvotes: 1

Nicola Cossu
Nicola Cossu

Reputation: 56407

How do we count them back together? LIKE: 1 2 3 4 5. i not want use of id in column database

select list_of_fields,@rn:=@rn+1 as row_num
from table,(select @rn:=0) as r order by id

Upvotes: 1

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 175098

This query should do the trick for you:

SELECT COUNT(*) as count FROM `table`

The result set would be

[count]
-------
5

Assuming you have 5 rows.


In order to manually count each row and display its index (without using ID), I would do something like

$counter = 1;
$stmt = $db->prepare('SELECT `field` FROM `table`');
$stmt->execute();
while($row = $stmt->fetch()) {
    echo "<b>{$counter}:</b> {$row['field']}";
    $counter++;
}

Upvotes: 0

cdhowie
cdhowie

Reputation: 169478

Just use this SQL query:

SELECT COUNT(*) FROM table_name

If you want to know how many rows were returned by another query, you can use the PHP mysql_num_rows function. (You could also just increment a counter for each row you process, but this function is handy if you need to know the number of records prior to enumerating the results.)

Upvotes: 4

Related Questions