Read tab delimited text file into MySQL table with PHP

Posted by Simon S on Stack Overflow See other posts from Stack Overflow or by Simon S
Published on 2010-04-30T15:24:57Z Indexed on 2010/04/30 15:27 UTC
Read the original article Hit count: 273

Filed under:
|
|

I am trying to read in a series of tab delimited text files into existing MySQL tables. The code I have is quite simple:

$lines = file("import/file_to_import.txt");

foreach ($lines as $line_num => $line) {
    if($line_num > 1) {
        $arr = explode("\t", $line);
        $sql = sprintf("INSERT INTO my_table VALUES('%s', '%s', '%s', %s, %s);", trim((string)$arr[0]), trim((string)$arr[1]), trim((string)$arr[2]), trim((string)$arr[3]), trim((string)$arr[4]));
        mysql_query($sql, $database) or die(mysql_error());
    }
}

But no matter what I do (hence the casting before each variable in the sprintf statement) I get the "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1" error.

I echo out the code, paste it into a MySQL editor and it runs fine, it just won't execute from the PHP script.

What am I doing wrong??

Si

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql