0

How can i use mysql_fetch_array / mysql_fetch_row results to create a csv file where each row records are csv and next record is in new line.

I tried this:

$query = "SELECT * FROM myTable DESC LIMIT 10";

$result = mysql_query($query, $conn);
$resultRows = mysql_num_rows($result);

if($resultRows < 1) {
    return array('query' => $query, 'NumberOfRows' => $resultRows, 'status' => 'failure');
};

$rowResult = mysql_fetch_array($result);
//var_dump($rowResult);exit;
foreach($rowResult as $row){

    $resultSet = $row['firstname'];
    $resultSet .= ',' . $row['lastname'];
    $resultSet .= ',' . $row['email'];
    $resultSet .= ',' . $row['phone'];
    $resultSet .= ',' . ($row['address1']);
    $resultSet .= '\n';
    //var_dump($resultSet);exit;
}
2
  • 1
    So, what error did you got there? Commented Jul 25, 2012 at 22:45
  • i am not getting results @ all Commented Jul 25, 2012 at 22:47

3 Answers 3

2

I believe the newline character must be in double quotes.

$resultSet .= "\n";

Probably just omitted from the code for length reasons, but be sure you're echoing $resultSet after the foreach.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, the escape sequences between double quotes will be interpreted as special characters
1

If you want the file to download as a CSV then you would include the following headers

header("Content-type: application/x-msdownload");
header("Content-Disposition: attachment; filename=extraction.csv");
header("Pragma: no-cache");
header("Expires: 0");

Then for the csv section you would use something like the following:

echo "FirstName,LastName,Email,Phone,Address\r\n"; //header
while($row = mysql_fetch_array($result)){
  echo "\"$row[firstname]\",\"$row[lastname]\",\"$row[email]\",\"$row[phone]\",\"$row[address]\"\r\n";
} 

But if you just wanted to create a file you would use something like the following:

$fp = fopen('file.csv', 'w');

while($row = mysql_fetch_array($result)){
   fputcsv($fp, $row);
}

fclose($fp);

Comments

0

Here is a good resource: http://www.codehive.net/PHP-Array-to-CSV-1.html

Usage:

$csv_data = array_to_scv($array, false);
print_r($csv_data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.