The Code:
PHP Code:
$fp = fopen('serialnumdb.txt','a+');
if (!$fp) {echo 'ERROR: Unable to open file.'; exit;}
while (!feof($fp)) {
$line = fgets($fp,1024); //use 2048 if very long lines
list ($SerialDBContents) = split ('\|', $line);
echo "Database number: $SerialDBContents";
}
$reviewNum = $SerialDBContents + 1;
$reviewSerialKey = "$reviewNum\n";
echo "<br />reviewSerialKey: $reviewSerialKey";
fwrite ($fp, $reviewSerialKey);
fclose($fp);
The Explanation:
OK, this is the code that's not working. I don't know why, it just doesn't.
Here's what it does, line by line.
1. Opens the database called "serialnumdb.txt" with an open at end of file for reading and writing.
2. Error message if database fails to open.
3.
4. Don't really know what this does...
5. This one too.
6. Something about making a variable with splitters the | and \ characters, and then a variable called $line.
7. Tells you what the database contains.
8.
9.
10. Makes it so that the variable $reviewNum is $SerialDBContents + 1, so that serialnumdb.txt only contains numbers. Originally the file is blank, and the script adds one to it, so that the next line on the database is 1, and the next time someone submits the form, it's 2, and 3, and 4...
11.
12. Now makes it so that a new variable is made, called "reviewSerialKey", and it is equal to $reviewNum (which is the $SerialDBContents + 1 value) plus an \n, which makes a line break in the database.
13.
14. Now, an fwrite writes into the database the $reviewSerialKey variable, which is the $reviewNum with the \n.
15.
16. Here, an fclose just closes the database.
The Problem:
With one visit to this script, here is what is entered into the database:
Yes, with the enter space at the end. (You can't tell with these code boxes, but after the last 1, there is a blank line)
Isn't there only supposed to be one 1? Apparently not.
Here's what the database looks like if I run the script again, without clearing the database:
This time with no enter space at the end. (Although it looks like it with these code boxes)
It just doubled it! WTH?
What I want this script to do is:
1. Open the blank file which is serialnumdb.txt
2. Read the last line of it (which now is nothing)
3. Add 1 to that nothing, so now when you submit that to the database, the database should contain the number 1 on a new line
4. Submit that into the database.
5. Close the database
That's what I've done, right? I think so...