I am trying to work with some text files here. What I do is go to my MySQL database and retrieve all rows. From there I go through each record with a for loop. Then I go through each column with a nested for loop. Inside the nested for loop I write each columns value to the text file. The problem that I am having is have the returns(\n) entered in the correct place.
My MYSQL table has these values.
|10000000001|John Doe |23658 |123658 |
I want to go through that record and write to a text file to make it look like:
10000000001John Doe 23658 123658
10000000002John Doe 23698 456698
Here is my script:
// String Pad function
// Used to ensure that stings occupy the correct fixed-field length
function stringpad( $fieldLen, $string ) {
// Add spaces to end of string if is less than column width
if ( strlen($string) < $fieldLen )
$string = str_pad( $string, $fieldLen );
// Date Format YYYY-MM-DD changed to YYYMMDD
elseif ( ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $string, $ereg) )
$string = $ereg[1] . $ereg[2] . $ereg[3];
else
$string = $string;
// Return edited value
return $string;
}
// GET variables
$dbName = $_GET["dbname"];
$tbName = $_GET["tbname"];
$fName = "/somedir/" . $_GET["fname"] . ".txt";
// Select databse and Query
mysql_select_db($dbName, $link);
$result = mysql_query("SELECT * FROM $tbName");
// Select and Open file for writing
$file = fopen($fName, "w");
// Dynamic Script Variables
$numRecs = mysql_num_rows($result);
$fields = mysql_list_fields($dbName,$tbName,$link);
$numCols = mysql_num_fields($fields);
// For each of the records
for ($x=0; $x<$numRecs; $x++) {
$row = mysql_fetch_row($result);
// For each of the columns
for ($y=0; $y<$numCols; $y++) {
// Set an array value equal to each of the column values
$textArray[$y] = $row[$y];
// Get column width/size and send with value to stringpad function to be padded
// for correct fixed field length
$fieldLen = mysql_field_len($fields, $y);
$paddedStr = stringpad( $fieldLen,$textArray[$y] );
// Write values to text file
fwrite( $file, $paddedStr );
}
}
// Close open file
fclose($file);
// Free result and close MySQL Link
mysql_free_result($result);
mysql_close($link);
Obviously this script is used for more than one table with values retrieved from the URL.
I hope that you can help??😕