CSV import help

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
bcpaul
Forum Newbie
Posts: 3
Joined: Mon Aug 04, 2008 12:54 am

CSV import help

Post 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
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: CSV import help

Post 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
User avatar
Bill H
DevNet Resident
Posts: 1136
Joined: Sat Jun 01, 2002 10:16 am
Location: San Diego CA
Contact:

Re: CSV import help

Post 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.
bcpaul
Forum Newbie
Posts: 3
Joined: Mon Aug 04, 2008 12:54 am

Re: CSV import help

Post by bcpaul »

Thanks, ill give it a try
Post Reply