Question

I'm pretty sure, a common problem but am looking for the best practice solution.

I have a legacy database, for which I have written a script to migrate the data.

In my script I have the following:

$select = $dbh->query("SELECT CollectionID, CollectionCode, Name FROM $db_local.collection");
  while ($collection_row = $select1->fetch (PDO::FETCH_ASSOC)) {
    $collection_id = $collection_row['CollectionID'];
    $collection_code = !empty($collection_row['CollectionCode']) ? "'{$collection_row['CollectionCode']}'" : "NULL";
    $collection_name = !empty($collection_row['Name']) ? "'{$collection_row['Name']}'" : "NULL";

    $dbh->exec("INSERT INTO $db_remote.cdrs_collectiononline (
        collection_id, 
        collection_code, 
        collection_name
        ) VALUES (
        $collection_id, 
        $collection_code, 
        $collection_name
        )");
} 

This is all fine until I run across this row:

| CollectionID | CollectionCode | Name                                |
+--------------+----------------+-------------------------------------+
|         1032 | MHNG           | Muséum d'Histoire Naturelle, Genève |

If I do this directly in mysql (note double quotes):

INSERT INTO cdrs_collectiononline (collection_id, collection_code, collection_name) VALUES ('1032', 'MHNG', "Muséum d'Histoire Naturelle, Genève")

It works. What is the best way to deal with the possibility of these latin characters using mysql pdo?

Any help much appreciated.

Was it helpful?

Solution

try :

$collection_name = addslashes(mysql_escape_string($collection_name));

or :

$dbh->exec("INSERT INTO $db_remote.cdrs_collectiononline (
        collection_id, 
        collection_code, 
        collection_name
        ) VALUES (
        '".$collection_id."', 
        '".$collection_code."', 
        '".$collection_name."'
        )");

OTHER TIPS

Little bit late but it can help somebody else !

It would be better to use the pdo prepare and bindParam : http://fr2.php.net/manual/fr/pdostatement.bindparam.php

It'll escape the character according to the type you choosed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top