I have written a HTML form to collect user's inputs for an order and also a PHP program to receive the order when Submit button is pressed. In addition I got to update a text file stored on the web server to reflect the order items. Can anyone explain how am I to go about updating a text file stored on the server? Thanks..
4 Answers
You should lock the file to protect the file from getting clobbered by concurrent updates sent by several users. There is a full example of locking and writing to a file in the flock function documentation: http://es.php.net/manual/en/function.flock.php
Or, to save yourself the trouble, use a proper database. SQLite is easy to use and requires no setting up: http://es.php.net/manual/en/book.sqlite3.php
Comments
Use fwrite:
$fp = fopen('data.txt', 'w');
fwrite($fp, $yourData);
fclose($fp);
UPDATE:
If I understood you right you need something like this:
if(!empty($noOfApples)){
$fp = fopen('data.txt', 'w+');
$count=fread($fp,filesize('data.txt'));
$count+=$noOfApples;
fwrite($fp, $count);
fclose($fp);
}
7 Comments
fopen (php.net/fread), increase value of file and write again into that file. If I got you then it need to work.$_POST variable (if you have method="post" in your form attributes). You just need to check if(isset($_POST['yourVar'])){/*Do some action*/}. Update the question with your form HTML code, and I'll send you some simple solutionSimplest way to do this AND preserve array structure of form fields is to dump $_POST via serialize.
Write example, after a user clicks submit:
file_put_contents('myfile.txt', serialize( $_POST ) );
Read example:
$data = unserialize(file_get_contents('myfile.txt'));
The form field would look something like:
<input type="text" name="myfield" value="<?php echo $data['myfield'] ?>" />
Alternatively, you can technically do $_POST = unseralize(file_get_contents(... but it will obviously overwrite anything that a user might input.
Comments
Just store the user input with the key which should be the input name and the value which should be the content user input. In this way, you can get the user input in an array.
Then you can translate the key-value pair into a string with serialize function. Now you can store the string into file with those code:
$fp = fopen('user{$id}.txt', 'w');//replace the {$id} with user id
fwrite($fp, $dateFromUser);
fclose($fp);
When you want to show the user input, just read the file and unserialize the string you get from the file and fill the input with the data which is stored in the array with the same key. When you want to update the user input just do the process above again.