PHP Scripts – WordPress Tutorials

Export mysql as csv is mostly needed when you need to import data to some other database, wherever you wanted to use.

I am giving my today’s release in that case, this is complete tested code to export MySQL as csv, whatever you need is to change the query section of this code.

I hope it would full fill all your requirements, it it does then do’t forget to comment.

Here it goes!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*

* establish database connection
*/

$conn = mysql_connect('server_name', 'server_username', 'your_password') or die(mysql_error());
mysql_select_db('Database_name', $conn) or die(mysql_error($conn));

$query = 'SELECT * FROM users';

$result = mysql_query($query, $conn) or die(mysql_error($conn));

/*
* send response headers to the browser
* following headers instruct the browser to treat the data as a csv file called export.csv
*/

header('Content-Type: text/csv');
header('Content-Disposition: attachment;filename=export.csv');

$row = mysql_fetch_assoc($result);
if ($row)
{
getcsv(array_keys($row));
}

 

while ($row)
{
getcsv($row);
$row = mysql_fetch_assoc($result);
}

/*
* echo the input array as csv data maintaining consistency with most CSV implementations
*/

function getcsv($fields)
{
$separator = '';
foreach ($fields as $field)
{
if (preg_match('/\\r|\\n|,|"/', $field))
{
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}

Random Posts


Categories: PHP, Web Development