[英]How do I count the number of rows in a MySQL Table?
I know that inside MySQL, you can use: 我知道在MySQL内部,您可以使用:
SELECT COUNT(*) FROM table
I have written the following code in PHP to display the number of rows on the page: 我已经用PHP编写了以下代码以显示页面上的行数:
$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.
可捕获的致命错误:在第19行的[Directory]中,类PDOStatement的对象无法转换为字符串。
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: 如果要计算行数,可以使用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 $rows->numrow
如果返回数据是一个对象
There are some easy and faster way to do this 有一些简单快捷的方法可以做到这一点
$sql = "SELECT COUNT(id) AS total_row FROM table_name";
$ sql =“ SELECT COUNT(id)AS total_row FROM table_name”;
$stmt = $conn->query($sql);$ stmt = $ conn-> query($ sql);
$stmt->execute();$ stmt->执行();
echo $count['total_row'];echo $ count ['total_row'];
$sql = "SELECT * FROM table_name";
$ sql =“ SELECT * FROM table_name”;
$stmt = $conn->query($sql);$ stmt = $ conn-> query($ sql);
$stmt->execute();$ stmt->执行();
$count = $stmt->rowCount();$ count = $ stmt-> rowCount();
echo $count;echo $ count;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.