Home >Backend Development >PHP Tutorial >Counters based on files and databases_PHP tutorial
Author: javaduke, originally from www.dukejava.com
File-based php counter
〈?
//php counter, based on file system.
function wincounter(){
//If the file does not exist, create it
if(!file_exists("count.txt"))
{
exec("echo 0>count. txt");
}
//Open our record file
//Get the file size and then extract the required data based on the size of the file
$fp=fopen("count.txt", "r+);
$FileSize=filesize("count.txt");
$Count=fgets($fp,$FileSize+1);
//Add 1 to the number of records and save them back In the file
$Count+=1;
fseek($fp,$Count);
fclose($fp);
//Return the current number of visits
return $Count;
}
? 〉
Database-based counter (mysql)?
1. First create the database:
CREATE TABLE counter{
counter int not null,
id int not null
}
INSERT INTO counter(counter,id) VALUES(0,1)
2. Counter code:
〈?
//PHP counter, based on MySQL database server
function. linuxcounter(){
//Connect to MySQL database
$conn=mysql_connect("localhost",phpbook","");
//Query the current number of views
//Pay attention to the way to obtain the results
$sql="select*from counter";
$result=mysql_query($sql,$conn);