#native_company# #native_desc#
#native_cta#

file processing; text and dat file creation

By koree monteloyola
on January 24, 2005

1. connect and execute your mysql query


$sql = "SELECT * FROM auth";
$res = mysql_query($sql);
$num = mysql_num_rows($res);

2. set the filepointer($fp) and specify the path and filename of the file to be created. In this part, fopen() requires 3 arguments but mostly you would only use 2 arguments: filename and directive. The directive sets the kind of processing to be done on the file. In this case “w”, means write (only). If the file doesn’t exists, it would attempt to create the file on the directory that you’ve specified, in this case it would be in the drive c-> “C:/” .


	$txtFile="C:/fileProcessing.txt";
	$fp = fopen($txtFile,"w");

3. by looping through the fetch command you can retrieve the data from your mysql database and save it in a single variable ($str) separated by the escape characters “rn”

r = carriage return
n = new line

“rn” = windows newline


	for($i=0;$i<$num;$i++){
		$row = mysql_fetch_array($res,MYSQL_BOTH);
		$name =$row['name'];
		$pass =$row[pass]."rn";
		$str .=$name.",".$pass;
	}

4. after storing the string into the $str variable, you could execute the fwrite() function, this line would write the string into your text file (fileProcessing.txt).

The fclose() would close the file pointer



	fwrite($fp,$str);
	fclose($fp);


5. Having this code would open a dialog box to save the text file (fileProcessing.txt) as “testing.DAT” in a location you desired


header("Content-type: text/htm");
header("Content-Disposition:attachment;filename=testing.DAT");
readfile($txtFile);

complete code


<?php
$conn = mysql_pconnect("localhost","root","password");
mysql_select_db("databaseName");
$sql = "SELECT * FROM auth";
$res = mysql_query($sql);
$num = mysql_num_rows($res);
if($num> 0){
	$txtFile="C:fileProcessing.txt";
	$fp = fopen($txtFile,"w");
	for($i=0;$i<$num;$i++){
		$row = mysql_fetch_array($res,MYSQL_BOTH);
		$name =$row['name'];
		$pass =$row[pass]."rn";
		$str .=$name.",".$pass;
		//.chr(13);
	}
	//echo $str;
	fwrite($fp,$str);
	fclose($fp);
	header("Content-type: text/htm");
header("Content-Disposition:attachment;filename=testing.DAT");
    readfile($txtFile);
}
?>