baumli1
asked on
How can I use PHP to update record in flat file
I have a flat file/PHP based poll system. Using a database is out of the question on the server it is on.
So far, I have it working except for updating a row with the new results. I can write to the file, I just don't know how to replace just that one row.
My text file is:
Poll ID||Question||Yes Votes||No Votes
107||Do you like this so far?||3||2
108||Do you like this so far?||3||2
109||Do you like this so far?||3||2
110||Do you like this so far?||3||2
111||Do you like this so far?||3||2
112||Do you like this so far?||3||2
113||Do you like this so far?||3||2
poll-vote.php.txt
So far, I have it working except for updating a row with the new results. I can write to the file, I just don't know how to replace just that one row.
My text file is:
Poll ID||Question||Yes Votes||No Votes
107||Do you like this so far?||3||2
108||Do you like this so far?||3||2
109||Do you like this so far?||3||2
110||Do you like this so far?||3||2
111||Do you like this so far?||3||2
112||Do you like this so far?||3||2
113||Do you like this so far?||3||2
poll-vote.php.txt
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
I've almost got it I think. I store all the contents in an array anyways. So after I'm done with all the processing, I can write the array back out to the flat file. The only problem now is that it just appends the array to the end of the flat file. Is there a way to empty out the file first, or just overwrite the contents with the new array?
To truncate the file, when you open the file the second time for writing, use:
fopen($filename, 'w');
The 'w' says:
"Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it." (http://www.php.net/manual/en/function.fopen.php)
fopen($filename, 'w');
The 'w' says:
"Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it." (http://www.php.net/manual/en/function.fopen.php)
ASKER
I actually never closed the file before writing to it again, so I used an "r+" when I first opened it. And that did the trick.
The only think I worry about it keeping the results file open, while other people may be accessing it.
The only think I worry about it keeping the results file open, while other people may be accessing it.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
There is no way to modify just a line in a file using php.
Make sense?