简体   繁体   中英

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. I used 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

You could separate this problem in to two

  1. I wanna know how to connect to mysql.
  2. I wanna know how to write that sql instruction.
 <?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应该可以解决问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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