Omar Al-Ali Omar Al-Ali - 5 months ago 9
PHP Question

I want to show "Users Online" in PHP

I got a bit of a problem here... This code only shows "1 User(s) Online" no matter how many are online. How do I fix that? Sorry for the title... I couldn't have "I need help with "Users Online" in PHP"

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