Reputation: 15484
im new to php and i hope you can help with an easy to get script. I have a txt file with this general format:
5TB-2A, L+, 1, 1695, 3255, l.jpg
5TB-2A, L-, 2, 1965, 3270, l.jpg
5TB-2A, D-, 7, 2970, 3270, l.jpg
5TB-2A, DFOK, 8, 3225, 3300, l.jpg
I want to read this txt file using php to retrive every data separated by "," into my MySQL table. Thanks for any help.
Upvotes: 1
Views: 885
Reputation: 48091
$lines=file($yourTxt);
foreach($lines as $v) {
$values = explode(',',$v);
PDO::prepare("INSERT INTO tbl (?,?,?,?,?)");
PDO::execute($values);
}
You can make a further check too see if the line just read is ok like:
foreach($lines as $v) {
$values = explode(',',$v);
if (count($values)!=6)
continue;
}
Upvotes: 4
Reputation: 45589
<?php
$results = array();
$rows = file($filename, FILE_SKIP_EMPTY_LINES);
if(empty($rows)){
// no data to parse
} else{
foreach($rows as $row){
$values = explode(', ', $row);
// keep only those values which have the 5 variables
if(count($values) > 5){
$results[] = $values;
}
}
}
// see if we have the correct data
print_r($results);
// ... then do your db inserts here
?>
Upvotes: 1
Reputation: 3972
You could use fgetcsv (http://php.net/fgetcsv) to read the file into an array in PHP and then write a query to insert it into the table one row at a time.
Upvotes: 1