How to make your own counter in PHP

墨辰丷
Release: 2023-03-25 18:06:01
Original
3371 people have browsed it

It is very simple to implement a counter with PHP. The implementation of the counter is divided into two stages: one is to implement counting; the other is to implement the display of numbers; and there are two ways to implement counting: one is file-based counting. ; The second is the counting method based on the database.

1. File-based counting

<?  
if(!file_exists("visit_log/counter.txt")){  
$fp=fopen("visit_log/counter.txt","w");  
fwrite($fp,"000001"); //这里假设最大为6位,你可以根据需要修改  
$counter="000001";  
fclose($fp);  
} //检查counter.txt文件是否存在,如果不存在则新建一个文件,并且写入“00001”。  
else{  
$fp=fopen("visit_log/counter.txt","r");  
$counter=fread($fp,6);  
//-----------------------------  
$counter+=1;  
//-----------------------------  
fclose($fp);  
switch(strlen($counter)){ //将counter变量格式化,这样显得美观  
case 1:  
$counter="00000".$counter;  
break;  
case 2:  
$counter="0000".$counter;  
break;  
case 3:  
$counter="000".$counter;  
break;  
case 4:  
$counter="00".$counter;  
break;  
case 5:  
$counter="0".$counter;  
break;  
}  
$fp=fopen("visit_log/counter.txt","w");  
fwrite($fp,$counter);  
fclose($fp);  
}  
?>
Copy after login

2. Database-based counting

<?  
$cn=mysql_connect("localhost","root","******");  
mysql_select_db("visit_log",$cn);  
$sql="select * from visit_counter";  
$result=mysql_query($sql,$cn);  
$record=mysql_fetch_array($result);  
if(empty($visited)){  
$counter=$record["amount"]+1;  
$sql="update visit_counter set amount=$counter";  
$result=mysql_query($sql,$cn);  
}  
mysql_close($cn);  
switch(strlen($counter)){ //将counter变量格式化  
case 1:  
$counter="00000".$counter;  
break;  
case 2:  
$counter="0000".$counter;  
break;  
case 3:  
$counter="000".$counter;  
break;  
case 4:  
$counter="00".$counter;  
break;  
case 5:  
$counter="0".$counter;  
break;  
}?>
Copy after login

Summary:

The above two methods are used to implement the counting function. Careful netizens may see that the counter variable seems to be useless. In fact, it is the variable we use to display.

Related recommendations:

php’s counter program

PHP’s counter program: solve all possible problems Problem_PHP tutorial

php counter program_php basics

The above is the detailed content of How to make your own counter in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template