我想显示在线用户和用户的总数。但是,有两个简单的查询:
SELECT id FROM users;
和
SELECT id FROM users WHERE online=1;
这是我第一个statement
if($stmt = $mysqli->prepare("SELECT id FROM users"))
{
$stmt->execute();
$stmt->fetch();
$totalcount = $stmt->num_rows;
$stmt->close();
$stmt = null;
}
第二个:
if($stmt = $mysqli->prepare("SELECT id FROM users WHERE online=?"))
{
$requ = 1;
$stmt->bind_param("i", $requ);
$stmt->execute();
$stmt->bind_result($onlineUsers);
$stmt->fetch();
$count = $stmt->num_rows;
$stmt->close();
$stmt = null;
}
它只返回 0 作为用户和在线用户的总数。你怎么能进行这样的检查?
答案 0 :(得分:1)
不是选择所有行,而是执行SELECT COUNT(*)
查询,以便返回计数作为结果。实际上,您可以将两个查询合并为一个:
if ($stmt = $mysqli->prepare("SELECT COUNT(*), SUM(online = ?) FROM users") {
$requ = 1;
$stmt->bind_param("i", $requ);
$stmt->execute();
$stmt->bind_result($totalcount, $count);
$stmt->fetch();
$stmt->close();
$stmt = null;
}
答案 1 :(得分:0)
if($stmt = $mysqli->prepare("SELECT COUNT(id) FROM users WHERE online=?"))
$requ = 1;
$stmt->bind_param("i", $requ);
$stmt->execute();
$stmt->bind_result($onlineUsers);
$stmt->fetch();
echo $onlineUsers;
$stmt->close();
$stmt = null;