简体   繁体   English

使用PHP计算表中的行数

[英]count number of rows in table using php

I just want to count the number of rows in a table that already created in a database using php. 我只想计算已经使用php在数据库中创建的表中的行数。 I used mysqli(). 我使用mysqli()。 I need the number of rows in the table as the output. 我需要表中的行数作为输出。

 <?php
  $mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");

   /* check connection */
   if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
     exit();
   }

  if ($result = $mysqli->query("SELECT count(*) cc FROM tablename")) {

     /* fetch the first row as result */
     $row = $result->fetch_assoc();

    printf("Result set has %d rows.\n", $row['cc']);

   /* close result set */
    $result->close();
 }

 /* close connection */
 $mysqli->close();
?>

In fact it's a common question you can find the answer anywhere. 实际上,这是一个常见问题,您可以在任何地方找到答案。

Like, http://php.net/manual/en/mysqli-result.num-rows.php 就像http://php.net/manual/en/mysqli-result.num-rows.php

You could separate this problem in to two 您可以将此问题分为两个

  1. I wanna know how to connect to mysql. 我想知道如何连接到mysql。
  2. I wanna know how to write that sql instruction. 我想知道如何编写该sql指令。
 <?php
  $mysqli = new mysqli("hostname", "dbusername", "dbpassword", "dbname");

   /* check connection */
   if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
     exit();
   }

  if ($result = $mysqli->query("SELECT columnName from tablename")) {

    /* determine number of rows result set */
     $row_cnt = $result->num_rows;

    printf("Result set has %d rows.\n", $row_cnt);

   /* close result set */
    $result->close();
 }

 /* close connection */
 $mysqli->close();
?>

EDIT: 编辑:

$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];

Try simple query like: 尝试像这样的简单查询:

SELECT COUNT(*) AS count
FROM mytable

如果您不想在SQL使用COUNT ,则可以只选择所有行(SELECT id FROM table) ,然后使用PHP count()

你也只是这样做

 "SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "

如果要计算php中的行, mysqli_num_rows应该可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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