8月 19, 2014

PHP 的 Session 使用方法

<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  </head>

  <body>
    <?php
    
      /*   Table           Field
         +--------------+----------+
         |counter       |pageview  |
         +--------------+----------+-----+
         |sessionTablew |sessionID |time |
         +--------------+----------+-----+
      */
    
      $dbuser = "xxxx";
      $dbpass = "xxxx";
      $dbname = "counter";
      
      $conn = mysql_connect( "localhost", $dbuser, $dbpass);
      if (!$conn)
        die ("connect fail");
      mysql_query("SET NAMES 'utf8'");
      mysql_select_db($dbname, $conn);
      
           
      session_start();
      $_sessionID = session_id();

      $queryString = "SELECT * from sessionTable where sessionID='{$_sessionID}'" ;
      $rowCount = mysql_num_rows( mysql_query($queryString, $conn) );
      
      if ( $rowCount == 0 )  /* here comes new visitor */
      {        
        $datetime = date("Y-m-d, H:i:s");
        
        $queryString ="insert into sessionTable values ('{$_sessionID}', '{$datetime}')";
        mysql_query($queryString, $conn);
        
        $queryString = "SELECT * FROM counter ORDER BY pageview DESC";       
        $row = mysql_fetch_array( mysql_query($queryString, $conn) );
        
        $ori = $row['pageview'] ;
        $ori_plus = $ori +1 ;
        
        $queryString ="update counter set pageview='{$ori_plus}' where pageview='{$ori}'";
        mysql_query($queryString, $conn);
        echo "visitor:".$ori_plus;
      }
     
    ?>  
  </body>
</html>

沒有留言:

張貼留言