Test.text
abc,def,ghi,jkl,...
Is there anyway possible to insert each one to each row in database?
1 abc
2 def
...
Any suggest?
Assuming the commas are always the separator for values, you don't even need PHP.
Check out the page http://dev.mysql.com/doc/refman/5.0/en/load-data.html
An example you can start with is
mysql> LOAD DATA INFILE 'C:\path\data.txt' INTO TABLE db2.my_table;
Look at the php file_get_contents();
function.
http://php.net/manual/en/function.file-get-contents.php
Look at the php explode();
function.
http://php.net/manual/en/function.explode.php
This will get your string into an array which you can then insert into your database.
You can execute a MySQL INSERT
query using the mysqli_*
functions in php.
http://php.net/manual/en/mysqli.query.php
Depends on how big the Text.txt file is but if its small-ish then you can do it like:
<?php
$text = file_get_contents('Test.txt');
$arrayOfTxt = explode(',',$text);
foreach($arrayOfTxt as $value){
//Insert trim($value)
}
?>
If I'm not wrong, you can do that with explode
$file = file_get_contents('file.txt');
$var = explode(",", $file);
The $var
variable will be a array containing, in this case, 4 positions(0,1,2, 3) with this('abc','def','ghi','jkl').
No you can do a foreach
inserting the values on your table:
foreach($var as $x)
{
//YOUR INSERT GOES HERE. PASSING THE $x TO YOUR QUERY
}
Just complementing Breland answer, you could also do this directly with MySQL like this?
LOAD DATA INFILE '/test.txt' INTO TABLE test TERMINATED BY ','
And if necessary, you can add this: LINES STARTING BY 'xxx'
to define from where the insert will begin. It is useful in case you want to avoid some lines on your file.
$file = fopen('test.txt', 'r');
$csv_array = fgetcsv($file);
foreach ($csv_array as $csv_data){
//Do your insertion code here.
}