PDO + MsSQL + freetds = wrong characters in INSERT queries

721 views Asked by At

I've noticed a problem during SELECT queries in my internal project, regarding utf8 characters (šđčćž). After I'd fixed problem regarding freetds definition for charset and version in freetds.conf, I've started to receive right characters when I run SELECT queries.

But! Now I'm experiencing problem regarding INSERT/UPDATE queries and with SELECT query when I try to search fields with some of those characters (šđčćž), and that's only with PDO bindValue method.

For example, this is my code:

try {
$pdo = new \PDO(
      "dblib:host=$host:$port;dbname=$database",
      "$username",
      "$password"
   );
   $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
   echo "There was a problem connecting. " . $e->getMessage();
}

When I try insert values with following code, inserted values in database are right:

$query = "INSERT INTO dbo.TABLE (ID, NAME) VALUES (2, 'Beriša');";
$statement = $pdo->prepare($query);
$statement->execute();

//Result:
//2 Beriša

But, after using bindValue method (which I must use, as I work with Symfony2), problem happens:

$query = "INSERT INTO dbo.TABLE (ID, NAME) VALUES (?, ?);";
$statement = $pdo->prepare($query);
$statement->bindValue(1, 2, \PDO::PARAM_INT);
$statement->bindValue(2, 'Beriša', \PDO::PARAM_STR);
$statement->execute();

//Result:
//2 Beriša

Bellow, you can find my current freetds configuration:

[global]
    tds version = 8.0
    text size = 20971520
    client charset = UTF-8

Database charset coalition is Croatian_CI_AS. Unfortunately, I can't change that, as it's old database, designed to work with old application, and for that application I'm working on web presentation.

1

There are 1 answers

0
Marko Milojevic On BEST ANSWER

I have found a solution after some time. It's not a perfect one, as I need to process each value (it's small fix for code, but still not clean enough). If anyone has another idea to make this one better, post it, pls.

$statement->bindValue(2, iconv('utf-8', 'Windows-1252', 'Beriša'), \PDO::PARAM_STR);