使用php计算表中的行数

时间:2014-11-26 08:49:48

标签: php sql count rows

我只想计算已使用php在数据库中创建的表中的行数。我用了mysqli()。我需要表中的行数作为输出。

6 个答案:

答案 0 :(得分:3)

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

事实上,这是一个常见的问题,你可以在任何地方找到答案。

赞,http://php.net/manual/en/mysqli-result.num-rows.php

您可以将此问题分为两个

  1. 我想知道如何连接到mysql。
  2. 我想知道如何编写sql指令。

答案 1 :(得分:1)

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

编辑:

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

答案 2 :(得分:0)

尝试简单查询,如:

SELECT COUNT(*) AS count
FROM mytable

答案 3 :(得分:0)

如果你想在php中计算行数,

mysqli_num_rows应该可以做到。

答案 4 :(得分:0)

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

答案 5 :(得分:0)

你也可以这样做

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