简体   繁体   中英

How do I count the number of rows in a MySQL Table?

I know that inside MySQL, you can use:

SELECT COUNT(*) FROM table

I have written the following code in PHP to display the number of rows on the page:

$sql = 'select * from users';
$data = $conn -> query($sql);
echo $data;

But when I run it, I get the following error:

Catchable fatal error: Object of class PDOStatement could not be converted to string in [Directory] on line 19.

I think the problem is that the returned value is not in string form. If that is correct, how would I be able to display the number of rows on the page?

If you want to count the rows you can do this with PDO:

$sql = 'select * from users';
$data = $conn->query($sql);
$rows = $data->fetchAll();
$num_rows = count($rows);

Well, you arent badly off, you are almost there:

$sql = 'SELECT COUNT(*) as numrow FROM users';
$data = $conn -> query($sql);
rows = $data->fetchAll();

Depending on the type of return data, you could use

$rows->numrow if the return data is an object

There are some easy and faster way to do this

  1. COUNT the column in query and fetch

$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];

  1. Using rowCount()

$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM