eboogyman wrote:
I have an HTML form with Firstname, lastname, address
I want to save the firstname, lastname and address appended to a file in say
results.txt, in the below format 1 entry per line...
MyFirstname,MyL astname,MyAddre ss
I know this is probebly easy, can someone help me with a code snippit that
does this?
You'll learn nothing by just copying some code you don't understand.
A few tips :
The form should call a php script in it's 'action' attribute, and the
'GET' or 'POST' method (prefer POST).
In the php script that's called, you can retrieve the 'firstname',
'lastname' and 'address' inputs values in the $_GET or $_POST array :
eg : $firstname = $_POST['firstname']
But you should first check that this value is set with isset() :
if (isset($_POST['firstname']) {
$firstname = $_POST['firstname'];
}
else {
// handle the error
}
You know have to append this to the file. This implies opening the file
in append mode, writing to the file, and closing the file. fopen(),
fwrite() and fclose() are your friends :
http://fr2.php.net/manual/en/function.fopen.php http://fr2.php.net/manual/en/function.fwrite.php http://fr2.php.net/manual/en/function.fclose.php
typically, it would do something like :
$file = @fopen('path/to/filename.ext', 'a');
if ($file == false) {
// could not open the file, so handle the error
}
else {
$buffer = "what you have to write\n";
$written = fwrite($file, $buffer);
fclose($file);
// check everything is ok
if ($written != strlen($buffer) ) {
// oops, there was a problem
}
}
To write the three informations on a single line, the simplest thing to
do is to concat them. Now dont forget that you may want to retrieve the
info, and know how to split the line into parts. The usual way is to
insert a separator before the fields. It's best to use a character (or
string) that has very few chances to be in a name or adress. Something
like a pipe ('|'), or a combination of unusual characterd (like '%%%')
should do it.
Now a last few things that might be useful to know:
- with something based on the above code, you won't check if there are
doubles in the persons list
- if you've got a problem when writing the file, it will be somewhat
messed up. It might be useful to backup the file before writing to it.
- the process (here the web server running PHP) must have write access
to the file
- if you don't want every script kiddie and its sister to do anything to
your file, you'd better protect it (this is usually done by some web
server conf file - usually named '.htaccess' if the server is Apache).
With all this and the PHP manual, there is no reason you couldn't write
the code by yourself !-)
HTH
Bruno