views:

136

answers:

2

How do I get all data from one row from mysql table exported into text files, but formatted this way:

  • one field under another, one per line
  • i would like to break that data into pieces and save for example 50 lines in file1.txt then next 50 in file2.txt and so on until end (it's not round number so last file would have less lines probably)
  • don't copy identical entries / remove duplicates

...using php script or just mysql console?

A: 

I hate doing peoples homework/work, but this one is just too easy.

 <?

 $row = mysql_fetch_array($rc);

 $nodupes = array();
 foreach ($row as $field)
 {
  $nodupes[$field] = $field;
 }

 $i = 1;
 $filenum = 0;
 $line = 50 ; // create new file ever 50 lines
            $text = "";
 foreach($nodupes as $field)
 {
  $i++;
  $text .= "$field\n";

  // to split into bite size peices
  if ($i % $line == 0)
  {
   $filenum++;
   $filename = "myfile_$filenum.txt";
   file_put_contents($filename,$text);
   $text = "";
  }
 }
 $filenum++;
 $filename = "myfile_$filenum.txt";
 file_put_contents($filename,$text);
 ?>

So eat today, and learn to fish another day!

Byron Whitlock
Henrik P. Hessel
You can't copy and paste forever. Eventually he will either learn, or hire someone like you or I to clean up his mess.
Byron Whitlock
I'd have used a 'SELECT DISTINCT' rather than manually remove the dupes, or at the very least, use PHP's built in array_unique.
Mark
it's neither work nor homework ;), i'm trying to learn on sample database
Phil
+2  A: 

I might do it this way, using the command-line client:

$ mysql --user=XXX --password=XXX --batch --skip-column-names \
  -e "SELECT userid, displayname FROM Users" stackoverflowdb | \
split -l 50 -a 5 - "result."
Bill Karwin
+1 Very cool. Reminids of those great perl one liners. Oh yeah, you forgot the distinct ;)
Byron Whitlock
Hacker!!! $5 says he won't understand half of what you wrote or how to run it.
Mark
Heh! See my favorite Perl hack here: http://stackoverflow.com/questions/303876/what-is-your-best-programming-experience/303992#303992
Bill Karwin