In order to write to a file from PHP you must be able to change the access of the directory. If you do not have access privileges, you can simple echo the data to the browser, then copy paste and upload the data manually. It is very convenient to be able to write files directly. We create a temporary file, then change the name when we are finished. That way, the files is never unavailable while we are writing it.
$save_path=$_SERVER[DOCUMENT_ROOT].'/patientData/'; #define target path
chmod($save_path, 0757); //make the directory writeable
$temp='file.tmp'; #define temporary target name
$dest='patients.txt'; #define final destination target name
$fp = fopen($save_path.'/'.$temp, "w", 0); #open for writing
//include your database connection and execute the query
$sql='SELECT * FROM Patients ORDER BY LastName,FirstName';
connect();
$result=mysql_query($sql);
mysql_close();
//loop through the results of the query and write each record to the file
$count=0;
while ($row=mysql_fetch_array($result))
{ extract($row); //Patient FirstName LastName Birthdate Gender
$data=$LastName.','.$FirstName;
fputs($fp, $data.chr(13)); #write all of $data to our opened file with a line feed
$count++;
}
fclose($fp); #close the file
#rename tmp file to dest file
if(file_exists($save_path.'/'.$dest)) unlink($save_path.'/'.$dest); //erase the current file
rename($save_path.'/'.$temp,$save_path.'/'.$dest); //rename the temporary file
chmod($save_path, 0755); //make the file read only
echo 'File created with '.$count.' records.';