<?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];
?>
我似乎无法找到如何获取accounts表中的行数(用户数),此代码根本不返回任何内容。我不确定我是否将正确的信息传递给'num_rows',或者我正在使用的查询是否正确。
答案 0 :(得分: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'];
答案 1 :(得分:-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
答案 2 :(得分:-1)
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;
}
}
?>
现在action.php可以按如下方式进行查询:
<?php include 'database.php'; ?>
$db = new database();
$query = "SELECT COUNT(*) FROM accounts";
$row = $db->select($query)->num_rows;
echo $row;
?>
完全conncetion.php:link