Making Usage Statistics in PHP - Showing the Statistics Table
(Page 3 of 7 )
Our next task is to code the site that will show us the saved statistics from the database. I will show two examples. The first one is text-based. Its goal is to allow you to review your visitors and visited sites. It's simple and quite obvious so you can get the data that you need from it.
This page consists of two tables. The first table shows all your visitors, each row represents a user. Data is retrieved from the database, using the MySQL GROUP BY clause. The table has the following columns:
1. Hostname
2. Number of visited pages
3. Clear data from this hostname

The picture above is my solution on my personal homepage. The 'X' signs in the last column are links referring to the code that deletes all visits from the given visitor. The code below shows the first table.
$q
='SELECT Host, COUNT(Site) AS cs FROM hits GROUP BY Host';
$visitor_r=mysql_query($q) or print(mysql_error());
echo "<h3>Visitors</h3><table width=100% border=1><tr>n".
"<td><b>Hostname</td>n".
"<td><b>Visited pages</td>n".
"<td align=center><b>Clear all from this visitor</td></tr>n";
while ($visitor=mysql_fetch_array($visitor_r))
echo "<tr><td>".$visitor['Host']."</td>n".
"<td>".$visitor['cs']."</td>n".
"<td align=center><a href=?op=stat&delhost=".
urlencode($visitor['Host']).">X</a></td></tr>";
// This link is to delete the visited pages of this user
// Note urlencode() which is because the string
// that will be queried as an URL
echo "</table>";
The second table shows all the page impressions, directly from the database. Columns are:
- Visited page
- Hostname
- Date

Clicking on the visitor's hostname in the table above clears the data, like the previous query (the links refer to the same piece of code).
In the first column there is the title of the HTML, but it's a link using the saved URL.
And now let's see the code for the second table:
$q
='SELECT Title, Site, Host, Date FROM hits
ORDER BY Date DESC, Host';
$page_imp_r=mysql_query($q) or print(mysql_error());
echo "<h3>Page impressions</h3>".
"<table width=100% border=1><tr>n".
"<td><b>Visited page</td>n".
"<td><b>Hostname</td>n".
"<td><b>Date</td></tr>n";
while ($page_imp=mysql_fetch_array($page_imp_r))
echo "<tr><td><a href=?".$page_imp['Site'].">".
$page_imp['Title']."</a></td>n".
// Link to the page
"<td><a href=?op=stat&delhost=".$page_imp['Host'].">".
$page_imp['Host']."</a></td>n".
"<td>".$page_imp['Date']."</td></tr>";
echo "</table>";
Next: Showing Figures Based on the Statistics >>
More PHP Articles
More By Adam Szanto