...

View Full Version : Write data from DB to txt file



Serex
06-21-2005, 01:28 PM
Hey. I have a question that may be simple to some but has confused me.

I have a script that queries a database and pulls a list of names out of the table. The query is fine i have it echoed on my page above were the txt file is included so i can compare the two results

I am trying to get it so that when i submit a form on the page. it writes the values of the db query into the file. so far i have had only success... just briefly with writing to the end of the file so it doesnt erase what it has already written in that session.

what i want basically is for the content of my bd query to be written to a txt file so the txt file is updated whenever i submit the form. also if possible id like the script to create the file if it isnt already there.

so far i have:



if ($_POST['Submit'])
{
// if the button is pressed

// write to the file
$fp = fopen( "names.txt" , "a+" );

while ($i < $num)
{
$name = mysql_result($result,$i,"name");
fwrite( $fp, $name );
$i++;
}

fclose( $fp );
}
else
{
// do nothing
}


$i is declared above and is used to compare the number of rows with the counter.

any help would be great. thanks

Fou-Lu
06-21-2005, 04:08 PM
From what I see, you don't have enough information to correctly do this. However, you mentioned that it works fine so I'm no concerned about your generation.
In order to overwrite your current text file, you need to use 'w+' as your mode, as it will truncate the current file and put the file pointer to the beginning. 'a+' will point to the end. Also, I'd recommend using a 'b' at the end of your mode for compatilbility with windows, and remember your linebreaks are different depending on your server OS - \n for *nix, \r\n for windows, and \r for mac.

delinear
06-21-2005, 04:17 PM
Also, fopen will automagically attempt to create the file (with most modes, including w+) if the file doesn't exist and it has permission. Just make sure you chmod the directory first so the file can be created. Of course, you could use php to set the permissions for you for the duration of the script then change them back afterwards for security, but you probably ought to just get it working first before you go there.

Serex
06-22-2005, 01:38 AM
Thanks for your replies and suggestions, will take them into consideration. I figured out why it wasn't working. I had been using $i for an above loop so all i needed to do was declare a new var $j and loop through the data using that var instead.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum