Search code examples
phpmysqlcsvescapingapostrophe

Trouble Escaping Apostrophe in PHP CSV Upload with fgetcsv()


I am uploading email addresses from a CSV file, via fgetcsv(), into a MySQL database. The problem that I am running into is that I cannot escape email addresses containing an apostrophe (or single quote).

So, O'[email protected] will not become O\'[email protected].

I know that this is supposed to happen, however I have been unable to find a working solution to escape the apostrophe. Can someone offer me any help? Here is my code:

while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
            {

                $num = count($data);
                $row++;
                for ($c=0; $c < $num; $c++) {
                    //echo $data[$c] . "<br />\n";
                    $clean_value = cleanse($data[$c]);

                    if(validEmail($clean_value)){
                        $query = mysql_query("INSERT INTO addresses (lid, email_addresses) VALUES ('$lid', '$clean_value')");
                    }else{
                        if($clean_value != ""){
                            $invalid_addresses .= $clean_value.', ';
                        }
                    }

                    /*if(mysql_error()){
                        $failed_addresses .= $data[$c].', '.mysql_error() . "<br />\n";
                    }*/
                }
            }

$query = mysql_query("INSERT INTO addresses (lid, email_addresses) VALUES ('$lid', \"". mysql_real_escape_string($clean_value) ."\")");

...This doesn't work for me


Solution

  • I don't know what your cleanse function does exactly, but why not use mysql_real_escape_string? That's what it's there for.