954,561 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

MySQL data to CSV using Fwrite

Hi, I'm currently working on a school project ..i was wondering if someone can help,
i'm creating a system which get's data from a database and creates a CSV file ..i Google a lot none of it helps, i want to get several rows from a table and write it as a .DAT format(passes as text) i know it's not a standard file format, but my teacher insists.by the way, for example i have a table which contains: full name , last name , age , sex. i want to get full name, last name .. using

mysql_fetch_array


method and write it in a .DAT format (which is in text)but i already try it, and it fetches the first row only please help :( .. here's my code so that i can explain myself clearly ..

$sql = "Select * from table_name where age = 10";
$result = mysql_query ($sql,$con) or die (mysql_error());
      $countrows= mysql_num_rows($result);
      $i =0;
$fp = fopen("files/ExampleDAT.DAT",'w');
      while ($row= mysql_fetch_array($result))
      {
       $details = $row['firstname'].','.$row['lastname'];
       fwrite($fp,$details);
      $i++;
      }
//or i'll try using fputcsv..:)


i'm newbie in PHP ..
Any suggestions might help, Thanks anyway!

cigoL..:)
Newbie Poster
19 posts since Jul 2011
Reputation Points: 10
Solved Threads: 2
 

try this

$sql = "Select * from table_name where age = 10";
$result = mysql_query ($sql,$con) or die (mysql_error());
      $countrows= mysql_num_rows($result);
 

      while ($row= mysql_fetch_array($result))
      {
       $list[] = $row['firstname'].','.$row['lastname'];
 
      }
      
      
      
       $file = fopen("files/ExampleDAT.DAT","w");

	foreach ($list as $line)
	  {
	  fputcsv($file,split(',',$line));
	  }
	
	fclose($file);
vaultdweller123
Posting Pro
554 posts since Sep 2009
Reputation Points: 42
Solved Threads: 75
 

Thanks, i'll try it .. i appreciate your help :) muchas gracias :)

cigoL..:)
Newbie Poster
19 posts since Jul 2011
Reputation Points: 10
Solved Threads: 2
 

It works ... though the split function is depreciated ..well it's okey i found out an alternative way ..

cigoL..:)
Newbie Poster
19 posts since Jul 2011
Reputation Points: 10
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: