php移动mysql数据的行数,如何使用PHP获取MySQL表中的行数?

I simply want to use PHP to get a count of the total number of rows in a MySQL table, and store the number in a variable called $count.

I prefer procedural code since my mind doesn't work in object-oriented fashion.

$sql="SELECT COUNT(*) FROM news";

$result = mysqli_query($con, $sql);

$count = mysqli_fetch_assoc($result);

echo $count;

The above is the latest I tried. Instead of giving me a number, it gives me the word "Array".

解决方案

You have a couple of options how to get the value of COUNT(*) from the SQL. The easiest three are probably this:

$sql = "SELECT COUNT(*) FROM news";

$result = mysqli_query($con, $sql);

$count = mysqli_fetch_assoc($result)['COUNT(*)'];

echo $count;

or using column alias:

$sql = "SELECT COUNT(*) as cnt FROM news";

$result = mysqli_query($con, $sql);

$count = mysqli_fetch_assoc($result)['cnt'];

echo $count;

or using numerical array:

$sql = "SELECT COUNT(*) FROM news";

$result = mysqli_query($con, $sql);

$count = mysqli_fetch_row($result)[0];

echo $count;

Do not use mysqli_num_rows to count the records in the database as suggested in some places on the web. This function has very little use, and counting records is definitely not one of them. Using mysqli_num_rows you would be asking MySQL to retrieve all matching records from database, which could be very resource consuming. It is much better to delegate the job of counting records to MySQL and then just get the returned value in PHP as shown in my answer.

I would also recommend to learn OOP, which makes your code cleaner and easier to read. The same with OOP could be done as follows:

$sql = "SELECT COUNT(*) FROM news";

$count = $con->query($sql)->fetch_row()[0];

echo $count;

If your query uses variables, then you could do a similar thing, but using prepared statements.

$sql = "SELECT COUNT(*) FROM news WHERE category=?";

$stmt = $con->prepare($sql);

$stmt->bind_param('s', $category);

$stmt->execute();

$count = $stmt->get_result()->fetch_row()[0];

echo $count;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值