為了方便測試需要記錄筆數多一點,可以按右鍵另存下載這個檔案【 table_viewcount.sql 】, 接著到 phpMyAdmin 中匯入。
<?php require_once('../shared/conn_pdo.php'); try{ $sql_str = "INSERT INTO viewcount (view_time, view_ip) VALUES (:view_time, :view_ip)"; $stmt = $conn->prepare($sql_str); $view_time = date('Y-m-d H:i:s'); $view_ip = $_SERVER['SERVER_ADDR']; $stmt->bindParam(':view_time' ,$view_time); $stmt->bindParam(':view_ip' ,$view_ip); $stmt->execute(); } catch (PDOException $e ){ die("Error!: ". $e->getMessage()); } } ?> <h1>View Count</h1>
以上設計很草率會無端不合理地灌水, 因此進一步修改, 並且加強練習路徑的問題 :
<?php $uri = $_SERVER['REQUEST_URI']; if( strchr($uri,'TS_webpage') ){ $path = '../shared/'; }else{ $path = 'shared/'; } require_once($path.'conn_pdo.php'); include_once($path.'assist.php'); if( !isset($_SESSION['vc']) ){ $_SESSION['vc']=1; try{ $sql_str = "INSERT INTO viewcount (view_time, view_ip) VALUES (:view_time, :view_ip)"; $stmt = $conn->prepare($sql_str); $view_time = date('Y-m-d H:i:s'); $view_ip = $_SERVER['SERVER_ADDR']; $stmt->bindParam(':view_time' ,$view_time); $stmt->bindParam(':view_ip' ,$view_ip); $stmt->execute(); } catch (PDOException $e ){ die("Error!: ". $e->getMessage()); } } ?> <h1>View Count</h1>
<p><?php include('TS_webpage/view_count.php'); ?></p>
<?php $nowY = date('Y'); $nowM = date('Y-m'); $nowD = date('Y-m-d'); try{ //瀏覽總人數 $sql_str = "SELECT * FROM viewcount"; $RS_vc = $conn->query($sql_str); $num_RS_vc = $RS_vc->rowCount(); //今年到訪人數 $sql_str = "SELECT * FROM viewcount WHERE view_time LIKE '$nowY%'"; $RS_vcY = $conn->query($sql_str); $num_RS_vcY = $RS_vcY->rowCount(); //本月到訪人數 $sql_str = "SELECT * FROM viewcount WHERE view_time LIKE '$nowM%'"; $RS_vcM = $conn->query($sql_str); $num_RS_vcM = $RS_vcM->rowCount(); //今天到訪人數 $sql_str = "SELECT * FROM viewcount WHERE view_time LIKE '$nowD%'"; $RS_vcD = $conn->query($sql_str); $num_RS_vcD = $RS_vcD->rowCount(); } catch (PDOException $e ){ die("Error!: ". $e->getMessage()); } ?> <p>網站至今瀏覽人數: 共有 <?php echo $num_RS_vc; ?> 位訪客 (今年 <?php echo $num_RS_vcY; ?> 人,本月 <?php echo $num_RS_vcM; ?> 人, 今日 <?php echo $num_RS_vcD; ?> 人)</p>