user1217709
user1217709

Reputation:

number of rows in a table

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

Upvotes: 4

Views: 19622

Answers (3)

rashedcs
rashedcs

Reputation: 3725

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

Upvotes: -2

Mihai Iorga
Mihai Iorga

Reputation: 39704

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

Upvotes: 12

hakre
hakre

Reputation: 197659

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

Upvotes: -1

Related Questions