Page 1 of 1

CSV import help

Posted: Mon Aug 04, 2008 1:02 am
by bcpaul
Hello

New to php but making progress. I have a csv file i am importing with:

Code: Select all

 
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
{
    $row++;
    $import = ("INSERT INTO foobar
(
        foo ,
        Name  ,
        bar  
    ) 
        values 
    (
        '$data[0]' ,
        '$data[1]',
        '$data[2]'
        
    )
    ");
 
 
one field is a persons Name and chugs along until it finds the name D'arcy or anything with a " or ' and throws an error
What would be a good way to deal with this?

Thanks in advance

Re: CSV import help

Posted: Mon Aug 04, 2008 1:39 am
by jaoudestudios
These values need to be encode otherwise it breaks the code.
Here is a facility to encode special characters...
http://www.jaoudestudios.com/entities.php

The php function used is htmlentities

Re: CSV import help

Posted: Mon Aug 04, 2008 8:55 am
by Bill H
I would suggest using mysql_real_escape_string() for strings being stored in a database.

The htmlentities() changes a quote mark to something like &345; in the string. while the mysql_real_escape_string() puts a backslash in front of it. There are advantages to both, but...

When reading the string back out of the database, use stripslashes() to remove the backslash.

Use html_entity_decode() for converting the html entities back to characters.

Re: CSV import help

Posted: Wed Aug 06, 2008 12:45 am
by bcpaul
Thanks, ill give it a try