count number of rows in table using php

2019-03-01 10:11发布

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 sql count rows
6条回答
贪生不怕死
2楼-- · 2019-03-01 10:54
 <?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.
查看更多
欢心
3楼-- · 2019-03-01 10:54

If you dont want to use COUNT in SQL, you can just select all rows (SELECT id FROM table) and then just use PHP count().

查看更多
smile是对你的礼貌
4楼-- · 2019-03-01 10:59

Try simple query like:

SELECT COUNT(*) AS count
FROM mytable
查看更多
Luminary・发光体
5楼-- · 2019-03-01 11:04

mysqli_num_rows should do the trick if you want to count the rows in php.

查看更多
看我几分像从前
6楼-- · 2019-03-01 11:04

also you simply do this

 "SELECT COUNT(*) AS `Rows`, `any column` FROM `tablename` GROUP BY `any column` ORDER BY `any column` "
查看更多
祖国的老花朵
7楼-- · 2019-03-01 11:13
 <?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];
查看更多
登录 后发表回答