Reputation:
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
Reputation: 320
There are some easy and faster way to do this
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
echo $count['total_row'];
$sql = "SELECT * FROM table_name";
$stmt = $conn->query($sql);
$stmt->execute();
$count = $stmt->rowCount();
echo $count;
Upvotes: 0
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
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