count the number of rows in mysql?

2019-09-02 14:09发布

问题:

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

回答1:

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


回答2:

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.)



回答3:

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;



回答4:

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++;
}