0

I need to import a large category .txt file to my mysql database. This text file has categories with 3 levels.

My text file look likes the example below (+/- 362 entries):

Business
Business = Business Innovation & Ideation = Innovation
Business = Economics
Business = Economics = Global Economics

My database table structure:

| id | cat | sub_cat | sub_sub_cat | 

What I want to do, is insert the categories in my database by php. The separator between the cat, sub and sub_sub cat is '='. What I want to reach is a something like a loop to insert this data to my database.

Thanks in advice.

With kind regards,

Nicky

2
  • Would Business be its own row with empty sub_cat and empty sub_sub_cat? Commented Jul 21, 2011 at 14:19
  • Yes, this would be the head category without a sub or sub_sub :) Commented Jul 21, 2011 at 15:05

1 Answer 1

0
$lines = file('category.txt'); // slurp file and split into an array by lines

foreach($lines as $line) {
    $parts = explode('=', $line); // decompose a line into individual sections
    $cat = mysql_real_escape_string(trim($parts[0])); // prepare sections for SQL
    $subcat = mysql_real_escape_string(trim($parts[1]));
    $subsubcat = mysql_real_escape_string(trim($parts[2]));

    $sql = "INSERT INTO yourtable (cat, sub-cat, sub_sub_cat) VALUES ('$cat', '$subcat', '$subsubcat');";
    mysql_query($sql) or die(mysql_error());
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank u very much! It look likes something is going wrong in my text file cause the insert wasn't good (4/5 entries in one cell of the table and nothing more) but your code looks to be good. I will let you know what's going wrong. Thank u very much
It's fixed, I had to catch to empty entries and set them to null. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.