PHP static counter?
I'm trying to create a script that will retain a count, even when it is called multiple times. This is to give un开发者_如何转开发ique IDs to certain things lines that the script is writing to a file.
For exmaple:
Monday I call the script and make 2 lines. The script gives ID 1 and 2 to those lines.
Friday I call the script again and make another line. The script gives ID 3 to this one.
etc
I would recommend using MySQL's auto increment feature.
Otherwise, store a flat file to store a running count (and lock it when in use to avoid concurrency issues).
You can't do this using static variables. The variable will lose its value if the scripts end. You could save your information in any storage type you want (MySQL, text file, xml ...).
How about reading the ID of the last line added and just increasing it by one? PHP isn't that strict with data types, so it's quite easy to do something like
$a = "1";
$a = (int)$a;
$a++;
// write $a for next line
If you're not already interacting with a database, the best answer for you might be SQLite. (SQLite is an SQL-accessible database stored in a flat file, allowing basic database functions without the need for a persistent server. It's accessed in PHP using PDO. http://us3.php.net/manual/en/ref.pdo-sqlite.php)
Otherwise, reading the file is probably the easiest way. There's an exponentially smarter and more efficient way to do this using fseek, but it's too early for me to figure it out.
<?php
$file = fopen($theFilename, 'r');
while ($line = fscanf($file)); //Ugly, but the last value of $line will be the last line of the file. (Super cumbersome if the file is big.)
$array = explode($line, '|') // Or whatever delimiter you're using to separate data
$last_id = $array[0] // Assuming the ID is in the first place in the file.
?>
精彩评论