user3092953 user3092953 - 8 months ago 34
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)


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



$conn = mysqli_connect('localhost','username','password','db name');//change credentials here
$online_users = array();

    $query = mysqli_query($conn,"SELECT DISTINCT(user_id), timestamp,page FROM user_actions WHERE timestamp > date_sub(now(), interval 5 minute)");

        while($row = mysqli_fetch_assoc($query)){
            $online_users[] = $row;
        echo "query error:-".mysqli_error($conn);
    echo "db connection error:-".mysqli_connect_error();


        <th>User Id</th>
        <th>Page Visited</th>
    <?php foreach($online_users as $online_user){?<
                <td><?php echo $online_user['user_id'];?></td>
                <td><?php echo $online_user['timestamp'];?></td>
                <td><?php echo $online_user['page'];?></td>
    <?php }?>

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.