number of rows in a table

2019-01-25 22:06发布

问题:

 <?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.

回答1:

$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'];


回答2:

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


回答3:

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



标签: php mysqli