user3092953 user3092953 - 2 months ago 6
MySQL Question

Number of entries in DB PHP

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:

Database Table

At the moment I have the following code

$query = mysql_query("SELECT user_id, timestamp FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");
$onlineUsers = mysql_num_rows($query);


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)

Answer

Since mysql_* is deprecated (php 5 onward) and removed in (php 7). So a mysqli_* example is her:-

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

Note:- If you want to show online user name also then you have to do JOIN query.

change table code accordingly.

It's a sample code. Read about SQL Injection and Cross-Site Scripting (XSS) attacks and modify it accordingly.