I converted this today to PDO and tested, and worked great while taking away the msqli code. I really can't remember if I ever shared this to the site of my own work but in case not, ignore bits go to code block 2.
You will need JQuery 2.1.1 +

And replace with (or create this as useronline.php):

require_once 'dbConfig.php';

$query = "SELECT * FROM users ORDER BY last_access DESC LIMIT 8";
$result = $db->query($query);

// Generate users data array
$userData = array();
if($result->num_rows > 0){
   while($row = $result->fetch_assoc()){
     
       $data['id']     = $row['id'];
       $data['value']  = $row['username'];
       $data['avatar'] = $row['avatar'];
           
       array_push($userData, $data);
   }
}

// Return results as json encoded array
echo json_encode($userData);


Now create dbConfig.php with:

<?
// Access security check
if (preg_match('/dbConfig.php/i',$_SERVER['PHP_SELF'])) {
   die;
}

// Database configuration
$dbHost     = "localhost";
$dbUsername = "user";
$dbPassword = "password";
$dbName     = "db";

// Create database connection
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);

// Check connection
if ($db->connect_error) {
   die("Connection failed: " . $db->connect_error);
}
?>



And place this in your [color=rgb(226, 80, 65)]header.php[/color] / [color=rgb(226, 80, 65)]footer.php[/color] file

<script>
function fetchOnlineUsers() {
   $(document).ready(function () {
       $.ajax({
           url: "usersonline.php",
           method: "GET",
           dataType: 'JSON',
           success: function (data) {
               var html_to_append = '';
               $.each(data, function (i, item) {
                   html_to_append +=
                       '<a title="' + item.value + '" href="/user/?id=' + item.id + '"><img style="width:45px;height:45px;border-radius:50%;margin-right:10px;" src="[color=rgb(226, 80, 65)]https://www.YOUR_URL.com/'[/color] + item.avatar + '" /></a>';
               });
               $("#online").html(html_to_append);
           }
       });
   });
}

fetchOnlineUsers(); // This will run on page load

setInterval(function(){
   fetchOnlineUsers() // this will run after every 15 seconds
}, 15000);
</script>


And put this somewhere you like in your theme:

  <!-- AJAX Users Online - 15sec interval -->
 <div id="online" style="height:45px;width:470px;padding-bottom:10px"></div>


** First code section is if i've already posted it, I've updated this away since to be secure.