Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can fetch a list of all logged in users by querying the sessions table. I'm assuming you're using Drupal 6.</p> <pre><code>&lt;?php $result = db_query('SELECT uid FROM {sessions} WHERE uid != 0'); $users = array(); while($user = db_fetch_array($result)) { $users[] = user_load($user); } </code></pre> <p>The query excludes sessions for <code>uid = 0</code> as these are anonymous users. <code>$users</code> is the array of user objects as described in the <a href="http://api.drupal.org/api/global/user" rel="noreferrer">Drupal API Docs</a>.</p> <p>You can optimize this if you already know what part of the user objects you will use (e.g. just the user id and name) by removing the user_load() in while loop and adding to the query a join with the users table, as each user_load() makes one additional query. The following would get you a list of logged in users' id and names:</p> <pre><code>&lt;?php $result = db_query('SELECT u.uid, u.name FROM {sessions} s INNER JOIN {users} u ON u.uid = s.uid WHERE s.uid != 0'); $users = array(); while($users[] = db_fetch_array($result)); </code></pre> <p>Since logged in users never time out (you can stay logged in indefinitely), it may be useful to exclude logged in users who haven't accessed the site in a while (i.e. maybe an hour of inactivity):</p> <pre><code>$timestamp = time - 3600; // 3600s is one hour. $result = db_query('SELECT uid FROM {sessions} WHERE uid != 0 AND timestamp &gt;= %d', $timestamp); </code></pre> <p>You might also want to limit how many users to return. For example, maybe you want to grab - at most - the last 10 logged in users who accessed the site:</p> <pre><code>$limit = 10; // Limit to the last 10 users. $result = db_query_range('SELECT uid FROM {sessions} WHERE uid != 0 ORDER BY timestamp DESC', $timestamp, 0, $limit); </code></pre> <hr> <p>As an aside, if you're going to be using <a href="http://en.wikipedia.org/wiki/Magic_number_%28programming%29" rel="noreferrer">magic numbers</a> (like $limit or the 3600s), you should make them persistent using variable_set(), variable_get(), and variable_del().</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload