Counting rows (SOLVED)

Need help with an engine or coding not on the list? Need help with a game or the website and forums here? Direct all questions here.
Post Reply
User avatar
SpiritWebb
Posts: 3107
Joined: Sun Jul 12, 2009 11:25 pm

Counting rows (SOLVED)

Post by SpiritWebb »

I know the subject is a little easy, however in my database I have a field called 'online' set to enum '0','1' and when they log out, it sets it as 0 and when they sign in, it sets it to one.

My question is, how do I count the rows in the database to ONLY count the ones set to 1? That way it can count how many people are currently online. I have one that counts the amount of registered users, but now I need it to count only the ones online. Here is the snipet of code that is supposed to count the rows that only have 1 listed.

Code: Select all

<?php
      $sql = mysql_query("SELECT COUNT(1) AS online FROM players");
      $num1 = mysql_fetch_array($sql);
      $counts = $num1['online'];
	  echo ("$counts");
	  if($counts == 0)
	  {
		echo "0";  
	  }
      ?>
Image

Image
User avatar
SpiritWebb
Posts: 3107
Joined: Sun Jul 12, 2009 11:25 pm

Re: Counting rows

Post by SpiritWebb »

Nevermind, figured it out. Here is the result:

Code: Select all

<?php
      $sql = mysql_query("SELECT COUNT(*) AS online FROM players WHERE online='1'");
      $num1 = mysql_fetch_array($sql);
      $online = $num1["online"];
	  if ($online == 0)
	  {
		echo "0";  
	  }
	  if ($online >= 1)
	  {
		echo "$online";  
	  }
?>
Image

Image
User avatar
KyleMassacre
Posts: 573
Joined: Wed Nov 27, 2013 12:42 pm

Re: Counting rows (SOLVED)

Post by KyleMassacre »

Hmm I actually haven't touched MySQL in a while but I don't believe you need to fetch your data.

Code: Select all

$q = mysql_query("select id from users where online = '1'");
$r = mysql_num_rows($q);
echo $r;
 
Off topic and I am sure you know, but get rid of the mysql extension. It is so PHP 5.4 ;)
Post Reply

Return to “Advanced Help and Support”