1

I am using following code for importing data into database using txt file

while (!feof($handle)) // Loop til end of file.
{



    $buffer = fgets($handle, 4096); // Read a line.

    $data_array =explode("|",$buffer);//Separate string by the means of |

    $escaped_array = array_map('mysql_escape_string',$data_array);

    $escaped_array = '("'.implode('","',$escaped_array).'") ';


    if($i !=1) {
       echo $sql = 'INSERT INTO '.$tablename.' VALUES'.$escaped_array; 
        mysql_query($sql) ; //or die(mysql_error().$tablename);// use mysql insert query here
        //exit;
    }

    $i++;
} //end while

it inserting values like INSERT INTO PROVIDER_DEMOGRAPHIC VALUES("10000104","Sand","David","C","MD","Family Practice","","N","N","N","P","125\r\r\n") INSERT INTO PROVIDER_DEMOGRAPHIC VALUES("10000105","Stucky","Mitchell","B","MD","Family Practice","","N","N","N","P","101\r\r\n")

I donot want extra character in last fiels like \r\n\r Please tell me how i can trim it.

1
  • Use fgetcsv and set delimiter to | instead of the default , Commented Nov 28, 2013 at 4:00

1 Answer 1

1

You are reading the newline characters from the file, and may need to trim it

Use:

$buffer = fgets($handle, 4096); // Read a line.
$buffer = rtrim($buffer);
$escaped_array = array_map('mysql_escape_string',$data_array);

Warning: mysql_ function is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used.

Sign up to request clarification or add additional context in comments.

Comments

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.