Omar Al-Ali Omar Al-Ali - 3 months ago 13
MySQL Question

How to show users online in PHP?

This code only shows "1 User(s) Online" no matter how many are online. How do I fix that?

<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.');
$online = "1";
$query = "SELECT * FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_array($data);
$online=$row['online'];
echo '<div id="online-me" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>

Answer

use the count() of MySql also use mysqli_fetch_assoc instead of mysqli_fetch_array

something like this

<?php
$con = mysqli_connect($host, $username, $password , $database)
or die('Error connecting to MySQL server.'); 
$online = "1";
$query = "SELECT count(id) as 'total' FROM `users` WHERE online = '$online'";
$data = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($data);
$online=$row['total'];
echo '<div id="online-me" class="mydiv3"><center><span id="stats">'.$online.' User(s) Online!</span> </center></div>';
?>
Comments