Page 1 of 1

adding them up

Posted: Fri Apr 28, 2006 8:37 am
by elecktricity
okay so I got a db setup to record visitors IP's, im trying to figure out how to add how many times they visit like if IP: 127.0.0.1
comes 3 times it would say 3, sounds simple but there in a db row so id be something like:

Code: Select all

<?PHP
$result = mysql_query("SELECT * FROM logs");
while($row=mysql_fetch_assoc($result)) {
	$ips = $row['ip'];
}
print_r($ips);
?>
I have been working for like an hour trying to figure out how to add these up im really not sure, I was thinking the IP could be the variable and the number of hits could be what it equals or something:

Code: Select all

<?PHP
$result = mysql_query("SELECT * FROM logs");
while($row=mysql_fetch_assoc($result)) {
	if($$row['ip']=='') {
		$$row['ip']=1;
	}
	else {
		$$row['ip']++;
	}
}
?>
I read somewhere you could do that, although I havnt tested it, but even if id did work I wouldnt know all the variable names so yea any help would be great.

Posted: Fri Apr 28, 2006 8:44 am
by feyd
Look into the GROUP BY clause.

Posted: Fri Apr 28, 2006 8:45 am
by Weirdan
I'm not really sure this is what you're looking for, but anyway...

Code: Select all

<?php
$result = mysql_query("SELECT * FROM logs");
$ips = array();
while($row=mysql_fetch_assoc($result)) {
        if(empty($ips[$row['ip']])) {
            $ips[$row['ip']] = 1;
        } else {
            $ips[$row['ip']]++;
        }
}
print_r($ips);
?>
or just:

Code: Select all

select
  `ip`, count(*)
from 
  `logs`
group by
  `ip`

Posted: Fri Apr 28, 2006 9:12 am
by elecktricity
how do I output the "count(*)" part, it keeps saying I have an error when I try to echo it:

Code: Select all

echo $row[count(*)];
echo $row[count()];
echo $row[count];
echo $row[count($row['ip'])];
none of those work...

Posted: Fri Apr 28, 2006 9:17 am
by feyd
try doing a var_dump(), var_export() or print_r() of $row. You'll find out.

Posted: Fri Apr 28, 2006 9:29 am
by elecktricity
I used print_r and it said:
Array
(
  • [ip] => 127.0.0.1
    [count(ip)] => 162
)
so I decide to echo $row[count(ip)]; but it just displays nothing?

Code: Select all

<?PHP
$result = mysql_query("SELECT  `ip`, count(ip) FROM  `logs` GROUP BY `ip`") or die ( mysql_error ());
echo '<!--
';
while($row=mysql_fetch_assoc($result)) { 
	echo '	';
	echo $row['ip'];
	echo ' : ';
	echo $row[count(ip)];
	echo '
';
}
echo '-->';
?>
<!--
  • 127.0.0.1 :
    127.0.0.2 :
    127.0.0.3 :
-->

Posted: Fri Apr 28, 2006 9:32 am
by feyd
put it in a string.

Posted: Fri Apr 28, 2006 9:48 am
by elecktricity
I finally got this one to work:

Code: Select all

$result = mysql_query("SELECT `ip`, count(ip) AS mycounter FROM `logs` GROUP BY   `ip`");
whlie($row=mysql_fetch_assoc($result)) {
echo $row['ip'];
echo ': ';
echo $row['mycounter'];
echo '<br>';
}
added the "AS mycounter" found that somewhere from google