为了账号安全,请及时绑定邮箱和手机立即绑定

带有计数器的php id并保存文件

带有计数器的php id并保存文件

PHP
湖上湖 2023-04-15 10:34:57
我想在它前面做一个带有标准前缀的计数器:202000,然后计算 2020001、2020002、2020003 等。并且这些数据必须保存在我服务器上的文件或数据库或 txt 文件中,但不会事情。我尝试了很多,但我可以做到。我对 PHP 很陌生。我现在有了这段代码,但我有一些问题,所以只保存了最后一个数字,并且前缀是否被计数器替换,如果你超过 10,你会得到 2020010,我想要 20200010。无论如何,这是我的代码:  <!DOCTYPE html><html dir="ltr">  <head>    <meta charset="utf-8">    <title></title>  </head>  <body>    <?php    $file = 'counter.txt';    // default the counter value to 1    $before = uniqid('202000');    $counter = 1;    // add the previous counter value if the file exists    if (file_exists($file)) {        $counter += file_get_contents($file);    }    // write the new counter value to the file    file_put_contents($file, $counter);    echo $before + $counter;    ?></body></html>有人可以帮我吗?
查看完整描述

2 回答

?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

您不必在文件中保存实际前缀 (202000)。只需保存计数器(1、2、3、4、5 等)


<?php

$file = 'counter.txt';

$prefix = '202000';


//If file exists then grab content of file(nr) and add it with one else set counter=1

file_exists($file) ? $counter = file_get_contents($file)+1 : $counter = 1;


//This is the number you would like to use (2020001, 2020002 ... 20200010 etc)

$use_number = $prefix .  $counter;  


//Save counter value to file (1,2,3,4 etc...)

file_put_contents($file, $counter);  

?>


查看完整回答
反对 回复 2023-04-15
?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

您可以计算所有文件行,将它们用作计数器的基数


$file = 'someFiel.txt';


$counter = 0; // the file lines


$handle = fopen($file, "r");

while(!feof($handle)){

  $line = fgets($handle);

  $counter++;

}


fclose($handle); //close the file reader


$next_line_no = $counter + 1; // this will add 1 to your counter

然后只需添加您的前缀和下一行


$next_line = '202000' . $next_line_no;

您可以通过计算行数来对 MySQL 执行相同的操作,然后使用 counter + 1 再次添加前缀;


查看完整回答
反对 回复 2023-04-15
  • 2 回答
  • 0 关注
  • 78 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信