DB中的条目数 [英] Number of entries in DB PHP
问题描述
我创建一个函数来显示有多少用户现在在线。这是基于谁在过去5分钟内打开了一个页面。每个网页载入都会保存到我的数据库中,如下所示:
I am creating a function to show how many users are online now. This is based on who has opened a page within the last 5 min. Each page load is saved to my DB, below:
目前我有以下代码
$query = mysql_query("SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);
这只是总计行数,我如何做到这一点, ? (因此在上面的数据库片段应该是2不是5)
This is simply totalling the number of rows, how can I do this so it only counts a user_id once? (so in the above database snippet it should be 2 not 5)
推荐答案
由于 mysql _ *
已弃用(php 5以上)并在(php 7)中移除。因此,
mysqli _ *
示例如下: -
Since mysql_*
is deprecated (php 5 onward) and removed in (php 7). So a mysqli_*
example is here:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$conn = mysqli_connect('localhost','username','password','db name');//change credentials here
$online_users = array();
if($conn){
$query = mysqli_query($conn,"SELECT DISTINCT(user_id), timestamp,page FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
if($query){
while($row = mysqli_fetch_assoc($query)){
$online_users[] = $row;
}
}else{
echo "query error:-".mysqli_error($conn);
}
}else{
echo "db connection error:-".mysqli_connect_error();
}
?>
<table>
<tr>
<thead>
<th>User Id</th>
<th>timestamp></th>
<th>Page Visited</th>
</thead>
</tr>
<tbody>
<?php foreach($online_users as $online_user){?<
<tr>
<td><?php echo $online_user['user_id'];?></td>
<td><?php echo $online_user['timestamp'];?></td>
<td><?php echo $online_user['page'];?></td>
</tr>
<?php }?>
</tbody>
</table>
注意: - 如果你想显示在线用户名,那么你必须做 JOIN query
。
Note:- If you want to show online user name also then you have to do JOIN query
.
因此更改表格代码。
码。相应地修改它。
这篇关于DB中的条目数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!