user5005297
user5005297

Reputation:

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?

Upvotes: 0

Views: 60

Answers (3)

keviveks
keviveks

Reputation: 320

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;

Upvotes: 0

Nelson Owalo
Nelson Owalo

Reputation: 2414

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

Upvotes: 0

Jay Blanchard
Jay Blanchard

Reputation: 34416

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

Upvotes: 3

Related Questions