number of rows in a table

2019-01-25 22:09发布

 <?php
    include('connnect.php');
    db_connect();
    echo 'We\'re about to count some rows';
    $query = "SELECT COUNT(*) FROM accounts";
    $result = mysqli_query($mysqli,$query);
    $row = $result->fetch_row();
   echo $row[0];
  ?>

I can't seem to find out how to get the number of rows(users) in the accounts table, this code simply returns nothing. I'm not sure if I'm passing the right information into 'num_rows' or if the query that I'm using is correct.

标签: php mysqli
3条回答
放荡不羁爱自由
2楼-- · 2019-01-25 22:45

conncet.php

<?php
class database
{
  public $host = "localhost";
  public $user = "root";
  public $pass = "";
  public $db   = "db";
  public $link;

  public function __construct()
  {
     $this->connect();
  }

  private function connect()
  {
     $this->link = new mysqli($this->host, $this->user, $this->pass, $this->db);
     return $this->link;
  }

 public function select($query)
 {
    $result = $this->link->query($query) or die($this->link->error.__LINE__);
    if($result->num_rows > 0)
    {
      return $result;
    } 
    else 
    {
        return false;
    }
}
?>

Now action.php where query can be done as follows :

<?php  include 'database.php'; ?>
 $db = new database();
 $query = "SELECT COUNT(*) FROM accounts";
 $row = $db->select($query)->num_rows;
 echo $row;
?>

Full conncetion.php : link

查看更多
【Aperson】
3楼-- · 2019-01-25 22:49

What you ask for is pretty standard interaction with the Mysqli Result Object. One thing is the number of rows returned, and the other thing is to get the actual count value:

$query  = "SELECT COUNT(*) FROM accounts";
$result = $mysqli->query($query);

echo 'Number of rows: ', $result->num_rows, "\n"; // 1 in your case

list($count) = $result->fetch_row();

echo 'COUNT(*): ', $count, "\n"; // the value from the database
查看更多
贪生不怕死
4楼-- · 2019-01-25 22:55
$query = "SELECT COUNT(*) FROM accounts";
$result = mysqli_query($mysqli,$query);
$rows = mysqli_fetch_row($result);
echo $rows[0];

or

$query = "SELECT COUNT(*) AS SUM FROM accounts";
$result = mysqli_query($mysqli,$query);
$rows = mysqli_fetch_assoc($result);
echo $rows['SUM'];
查看更多
登录 后发表回答