4
 <?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];
  ?>

我似乎无法找到如何获取帐户表中的行数(用户),此代码根本不返回任何内容。我不确定我是否将正确的信息传递给“num_rows”,或者我使用的查询是否正确。

4

3 回答 3

10
$query = "SELECT COUNT(*) FROM accounts";
$result = mysqli_query($mysqli,$query);
$rows = mysqli_fetch_row($result);
echo $rows[0];

或者

$query = "SELECT COUNT(*) AS SUM FROM accounts";
$result = mysqli_query($mysqli,$query);
$rows = mysqli_fetch_assoc($result);
echo $rows['SUM'];
于 2012-09-23T16:22:59.310 回答
-1

您要求的是与 Mysqli 结果对象的非常标准的交互。一件事是返回的行数,另一件事是获取实际的计数值:

$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
于 2012-09-23T16:31:50.453 回答
-2

连接.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;
    }
}
?>

现在 action.php where 可以进行如下查询:

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

完整的 conncetion.php :链接

于 2017-11-19T19:37:16.160 回答