Tuesday, July 10, 2012

MySQL Selecting data into a file



MySQL Selecting data into a file

The SELECT statement can be used to write data from tables to a file.For this tutorial,i used previous table vehicle(page in MySQL standard deviance and variance). In most of FAQs people ask how to SELECT * INTO OUTFILE create or where is the out file etc.Here out file stores C:\xampp\htdocs as data.txt.
Following scripts write the data.txt file.

<?php
$username="root";
$password="";
$database="my_database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query =mysql_query("SELECT * INTO OUTFILE '{$_SERVER['DOCUMENT_ROOT']}/data.txt' FIELDS TERMINATED BY ','
LINES TERMINATED BY '\t' FROM vehicle");
$result = mysql_query($query);
?>
1,Toyota,8    2,Mercedes ,9    3,Volkswagen ,10    4,Volvo,12    5,Audi,6    6,Ford,7    7,Mitsubishi,8    8,Nissan,9   

Now,You can delete the data in vehicle table and load it again by using following scripts and this data.txt file.

<?php
$username="root";
$password="";
$database="my_database";
mysql_connect(localhost,$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$query =mysql_query("LOAD DATA INFILE '{$_SERVER['DOCUMENT_ROOT']}/data.txt' INTO TABLE vehicle FIELDS TERMINATED BY ','
LINES TERMINATED BY '\t' ");
$result = mysql_query($query);
?>

No comments:

Post a Comment