3.1. |
What to display? |
|
Aim: nothing less and nothing more than displaying the visits count on the site (home page) and on its major sections (Computer Basics,
Lazarus/Free Pascal Programming...) for the last 7 days. Approach: Reading the relevant data from the database and displaying it as a HTML
table.
|
|
3.2. |
What to do? |
|
To do:
- Create a PHP file, containing the standard HTML structure of all pages on my site.
- Include the PHP code that reads the database and, using the actual data, generates a HTML table.
Code preview for the PHP script:
- Determine the dates of the last 7 days.
- Read the visitors count for each URL and each of these dates from the database.
- Create a HTML table, using the actual data as cell values.
|
|
3.3. |
PHP code. |
|
You can view the code by opening the tab below. Or click the following link to download
the PHP script.
|
The 7 days visitors counting script (/sitestats/stats_7days.php). |
<?php
$user = 'stats'; $passwd = 'password';
$pdo = new PDO('mysql:host=localhost;dbname=statistics', $user, $passwd);
for ($i = 7; $i >= 1; $i--) {
$day = mktime(0, 0, 0, date("m"), date("d") - $i + 1, date("Y"));
$dates[7 - $i + 1] = date("Y", $day) . "-" . date("m", $day) . "-" . date("d", $day);
}
$firstdate = $dates[1]; $lastdate = $dates[7];
$sql = "SELECT site_url AS _site, access_date AS _date, access_count AS _count FROM web_sites, site_hits ";
$sql .= "WHERE web_site = site_id ";
$sql .= " AND access_date >= '$firstdate' AND access_date <= '$lastdate' ";
$sql .= "ORDER BY site_seqnum, access_date";
$sth = $pdo->query($sql);
if ($sth->rowCount() > 0) {
echo '<table border="1" cellpadding="5">';
echo '<tr>';
echo '<th>Site url</th>';
for ($i = 1; $i <= 7; $i++) {
$dateparts = explode('-', $dates[$i]);
$date = $dateparts[2] . '.' . $dateparts[1];
echo '<th>' . $date . '</th>';
}
echo '<th>Total</th>';
echo '</tr>';
$oldsite = '';
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
if ($row['_site'] != $oldsite) {
if ($oldsite != '') {
for ($j = $i; $j <=7; $j++) {
echo '<td> </td>';
}
echo '<td align="right">' . $total . '</td>';
echo '</tr>';
}
echo '<tr>';
echo '<td>' . $row['_site'] . '</td>';
$oldsite = $row['_site'];
$i = 1; $total = 0;
}
while ($row['_date'] > $dates[$i]) {
echo '<td> </td>';
$i++;
}
echo '<td align="right">' . $row['_count'] . '</td>';
$i++; $total += $row['_count'];
}
for ($j = $i; $j <=7; $j++) {
echo '<td> </td>';
}
echo '<td align="right">' . $total . '</td>';
echo '</tr>';
echo '</table>';
}
else {
echo '<p>There are no site hits for the last 7 days...</p>';
}
?>
|
|
|
|
3.4. |
Running the script. |
|
Running the script (first the script as is in the download file, then the script included in my standard HTML code) on September,
16 on my local machine, by typing "localhost/sitestats/stats_7days.php" in the address field of my webbrowser, produces the
following output:
|
|
|