Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Writing to a file or database table.

Status
Not open for further replies.

jxfish2

Technical User
Jan 24, 2002
183
US
I'm a Systems guy, and new to PHP...

I've figured out how to create forms, and display the data back to the screen...

I want to write (or append if the file already exists) this same form data to a flat file, using my own field delimeters...

i.e.:

Name : Street : City : State: Zip

If I've defined the following variable in my script, how can I write it to the file?

$record = "${name}:${street}:${city}:${state}:${zip}";

I can easily display the output back on my screen:

print $record

Next, how would I add the same data to a database table?

Thanks in advance, and have a great day...
 
Can anyone furnish an example, using the information provided above?

TIA

Joe
 
The following code should work to dump your variable $record into text file. I havent tested it, or included any error detection ... but it should give you some ideas on file handling in PHP.


//open file for writing and place pointer at end of file
$fd = fopen("/path/to/filename.txt","a");
// write data to file
fputs($fp,$record,strlen($record));
// flush the output to the file
fflush($fp);
// close the file
fclose($fp);


More info on all PHP's filesystem functions are at:

Hokey
 
correction in code:

//open file for writing and place pointer at end of file
$fp = fopen("/path/to/filename.txt","a");
// write data to file
fputs($fp,$record,strlen($record));
// flush the output to the file
fflush($fp);
// close the file
fclose($fp);


misstyped the file pointer ;-)
 
Hi Hokey,

The above post is great, but I need some further information...

When I run the above script multiple times, the entries are appended to the file, but are not placed on their own separate line...

Each new line is appended directly on the end of the previously existing line...

Is there a control character of some type, such as a "\n" in a printf statement?

If so, at what point would I insert it into the above code?

1) at the end of the fputs line, or at the end of the fflush line?

TIA

Joe
 
before you even open the file pointer you could just append a newline (or carriage return & newline) at the end of the $record variable

$record .= "\n";

OR for a Windows text file

$record .= "\r\n";

 
Thanks Hokey...

I was playing with that exact thing, and just happened across the answer about 1 minute before you posted the answer...

Have a great weekend...

Joe
 
I've just spent two days searching for that info.
Bookmarks .= "tek-tips.com";
;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top