create account

How To Export MySql To CSV by bej

View this thread on: hive.blogpeakd.comecency.com
· @bej · (edited)
$8.00
How To Export MySql To CSV
#### What Will I Learn?
In this tutorial, I will explain you How To Export MySql To CSV very easily. 

#### Requirements
MySql Server

#### Difficulty
 Intermediate


#### Tutorial Contents
1. Assigning  the Mysql database & table
2. Creating the connection to the Mysql database-export.php
3. Creating 'exportMysqlToCsv' function-exportMysqlToCsv.inc.php

<html>
<p>In most of project&nbsp;mostly&nbsp;clients wants to export their database in to CSV / Eecel file. It will help us to make a simple record or in future we can also import the same data in to MySql database.</p>
<p>In this tutorial, I will explain you&nbsp;<strong>How To Export MySql To CSV </strong>very easily.&nbsp;</p>
<h2><strong>Export MySql To CSV</strong></h2>
<p><img src="https://steemitimages.com/DQmXaohkF1pw1rMMsYJ3mrzcLyP15nDtbXNKeEZbKz5jNQk/image.png" width="600" height="300"/></p>
<p>&nbsp;</p>
<h2>STEP 1:Assigning &nbsp;the Mysql database &amp; table.</h2>
<ul>
  <li>$host: Hostname or an ip adress. it is usualy <strong>localhost</strong>.</li>
  <li>$db: Mysql user account used to access the database.</li>
  <li>$user: this is the password for the Mysql user account.It is usualy&nbsp;<strong>root</strong>.</li>
  <li>$pass: this is the name of the Mysql database used.It is usualy&nbsp;blank.</li>
  <li>$table: The name of the table that you want from Mysql to csv.</li>
</ul>
<h2>STEP 2:&nbsp;Creating the connection to the Mysql database-export.php</h2>
<p>In this function, I will create a simple MySql database connection using the above&nbsp;assigning&nbsp;variable.Now as you can see we are calling here&nbsp;exportMysqlToCsv($table) function and passing the name of table. In Next step we will create this function.</p>

```
<?php

$host = 'localhost'; // MYSQL database host adress
$db = ''; // MYSQL database name
$user = ''; // Mysql Datbase user
$pass = ''; // Mysql Datbase password

// Connect to the database
$link = mysql_connect($host, $user, $pass);
mysql_select_db($db);

require 'exportMysqlToCsv.inc.php';

$table=""; // this is the tablename that you want to export to csv from mysql.

exportMysqlToCsv($table);

?>
```

<h2>STEP 3:&nbsp;Creating 'exportMysqlToCsv' function-exportMysqlToCsv.inc.php</h2>
<p>Create a php file and named it as 'exportMysqlToCsv.inc.php'.</p>

```
<?php

function exportMysqlToCsv($table,$filename = 'export.csv')
{
	$csv_terminated = "\n";
	$csv_separator = ",";
	$csv_enclosed = '"';
	$csv_escaped = "\\";
	$sql_query = "select * from $table";

	// Gets the data from the database
	$result = mysql_query($sql_query);
	$fields_cnt = mysql_num_fields($result);

	$schema_insert = '';

	for ($i = 0; $i < $fields_cnt; $i++)
	{
		$l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
			stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
		$schema_insert .= $l;
		$schema_insert .= $csv_separator;
	} // end for

	$out = trim(substr($schema_insert, 0, -1));
	$out .= $csv_terminated;

	// Format the data
	while ($row = mysql_fetch_array($result))
	{
		$schema_insert = '';
		for ($j = 0; $j < $fields_cnt; $j++)
		{
			if ($row[$j] == '0' || $row[$j] != '')
			{

				if ($csv_enclosed == '')
				{
					$schema_insert .= $row[$j];
				} else
				{
					$schema_insert .= $csv_enclosed .
					str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
				}
			} else
			{
				$schema_insert .= '';
			}

			if ($j < $fields_cnt - 1)
			{
				$schema_insert .= $csv_separator;
			}
		} // end for

		$out .= $schema_insert;
		$out .= $csv_terminated;
	} // end while

	header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	header("Content-Length: " . strlen($out));
	// Output to browser with appropriate mime type, you choose <img src="icon_wink.gif" alt=";)" class="wp-smiley">
	header("Content-type: text/x-csv");
	//header("Content-type: text/csv");
	//header("Content-type: application/csv");
	header("Content-Disposition: attachment; filename=$filename");
	echo $out;
	exit;

}

?>
```

<p>As you can see the code in this function we are passing the table name using $table&nbsp;variable. In this example default filename of the exported file is&nbsp;<em>export.csv.</em> you can change it as you like to append date.(ex.export-15-02-20182.csv)&nbsp;</p>
</html>

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@bej/how-to-export-mysql-to-csv">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍  , , , , , , , , ,
properties (23)
authorbej
permlinkhow-to-export-mysql-to-csv
categoryutopian-io
json_metadata{"community":"utopian","app":"utopian/1.0.0","format":"markdown","repository":{"id":24494032,"name":"mysql-server","full_name":"mysql/mysql-server","html_url":"https://github.com/mysql/mysql-server","fork":false,"owner":{"login":"mysql"}},"pullRequests":[],"platform":"github","type":"tutorials","tags":["utopian-io","mysql","database","tutorials"],"users":["bej"],"moderator":{"account":"vladimir-simovic","time":"2018-02-16T08:23:59.352Z","reviewed":true,"pending":false,"flagged":false},"questions":[],"score":0}
created2018-02-15 18:24:03
last_update2018-02-16 08:24:00
depth0
children3
last_payout2018-02-22 18:24:03
cashout_time1969-12-31 23:59:59
total_payout_value5.556 HBD
curator_payout_value2.440 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,451
author_reputation548,769,303,194
root_title"How To Export MySql To CSV"
beneficiaries
0.
accountutopian.pay
weight2,500
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id37,806,301
net_rshares1,505,198,586,791
author_curate_reward""
vote details (10)
@steemitboard ·
Congratulations @bej! You have completed some achievement on Steemit and have been rewarded with new badge(s) :

[![](https://steemitimages.com/70x80/http://steemitboard.com/notifications/firstpayout.png)](http://steemitboard.com/@bej) You got your First payout

Click on any badge to view your own Board of Honor on SteemitBoard.
For more information about SteemitBoard, click [here](https://steemit.com/@steemitboard)

If you no longer want to receive notifications, reply to this comment with the word `STOP`

> By upvoting this notification, you can help all Steemit users. Learn how [here](https://steemit.com/steemitboard/@steemitboard/http-i-cubeupload-com-7ciqeo-png)!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-bej-20180215t212753000z
categoryutopian-io
json_metadata{"image":["https://steemitboard.com/img/notifications.png"]}
created2018-02-15 21:27:51
last_update2018-02-15 21:27:51
depth1
children0
last_payout2018-02-22 21:27:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length676
author_reputation38,975,615,169,260
root_title"How To Export MySql To CSV"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id37,839,860
net_rshares0
@utopian-io ·
### Hey @bej I am @utopian-io. I have just upvoted you!
#### Achievements
- You have less than 500 followers. Just gave you a gift to help you succeed!
- Seems like you contribute quite often. AMAZING!
#### Suggestions
- Contribute more often to get higher and higher rewards. I wish to see you often!
- Work on your followers to increase the votes/rewards. I follow what humans do and my vote is mainly based on that. Good luck!
#### Get Noticed!
- Did you know project owners can manually vote with their own voting power or by voting power delegated to their projects? Ask the project owner to review your contributions!
#### Community-Driven Witness!
I am the first and only Steem Community-Driven Witness. <a href="https://discord.gg/zTrEMqB">Participate on Discord</a>. Lets GROW TOGETHER!
- <a href="https://v2.steemconnect.com/sign/account-witness-vote?witness=utopian-io&approve=1">Vote for my Witness With SteemConnect</a>
- <a href="https://v2.steemconnect.com/sign/account-witness-proxy?proxy=utopian-io&approve=1">Proxy vote to Utopian Witness with SteemConnect</a>
- Or vote/proxy on <a href="https://steemit.com/~witnesses">Steemit Witnesses</a>

[![mooncryption-utopian-witness-gif](https://steemitimages.com/DQmYPUuQRptAqNBCQRwQjKWAqWU3zJkL3RXVUtEKVury8up/mooncryption-s-utopian-io-witness-gif.gif)](https://steemit.com/~witnesses)

**Up-vote this comment to grow my power and help Open Source contributions like this one. Want to chat? Join me on Discord https://discord.gg/Pc8HG9x**
properties (22)
authorutopian-io
permlinkre-bej-how-to-export-mysql-to-csv-20180217t180848640z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-17 18:08:48
last_update2018-02-17 18:08:48
depth1
children0
last_payout2018-02-24 18:08:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length1,501
author_reputation152,955,367,999,756
root_title"How To Export MySql To CSV"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id38,316,219
net_rshares0
@vladimir-simovic ·
Thank you for the contribution. It has been approved.

You can contact us on [Discord](https://discord.gg/uTyJkNm).
**[[utopian-moderator]](https://utopian.io/moderators)**
properties (22)
authorvladimir-simovic
permlinkre-bej-how-to-export-mysql-to-csv-20180216t082406299z
categoryutopian-io
json_metadata{"tags":["utopian-io"],"community":"utopian","app":"utopian/1.0.0"}
created2018-02-16 08:24:09
last_update2018-02-16 08:24:09
depth1
children0
last_payout2018-02-23 08:24:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length172
author_reputation56,930,790,558,862
root_title"How To Export MySql To CSV"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id37,949,436
net_rshares0