0

I keep getting this error : PHP PDO : Charset=UTF8 : An invalid keyword charset was specified in the dsn string.

My code is like this

function ConnectToSQLAndGetDBConnSTRVar() {
    try {
    $dbname = "irina";
    $serverName = ".\SQLEXPRESS";  
    $username = "USERNAME";
    $pw = "PASSWORD"; 
    $dbh = new PDO ("sqlsrv:server=$serverName;Database=$dbname;charset=utf8","$username","$pw");
    return $dbh;
    } 
    catch (PDOException $e) {
    print "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
    }    
}

And it doesnt matter how I write utf8.. UTF8 or UTF-8 or utf-8 none of them work for me.. So what do i do please help me..

Mark
  • 1,376
  • 9
  • 16

2 Answers2

4

You can find the parameters accepted in the DSN string on this page of the PHP manual.

There is no Charset parameter in DSNs for the "SQL Server" PDO driver (with the DSN prefix sqlserv:).

Bear in mind that all PDO drivers have different DSN conventions, as they are passed directly to the driver and not normalised by PDO.

There is an alternative PDO driver for SQL Server called "PDO_DBLIB", which does take charset as a DSN parameter, but it has the prefix "sybase:", "mssql:", or "dblib:", depending on compilation options.

IMSoP
  • 89,526
  • 13
  • 117
  • 169
  • Sorry. Totally misread that. Deleted my obviously wrong comment. – Mark Sep 22 '13 at 20:38
  • Hey can you help me on how I install this on my IIS local server? i downloaded from here http://pecl.php.net/package/PDO_DBLIB a tgz file and i have no idea how i install this on my IIS local server.. – Avriel Moscovitz Sep 22 '13 at 21:24
  • 2
    The built-in SQL Server driver uses UTF-8 by default. There's no need to install some other driver in order to use UTF-8, and no need to specify the encoding in the first place unless you're using something other than UTF-8. – cHao Sep 23 '13 at 05:28
0

I had same error while following the instructions from here to prevent sql injections reading manual - it is said that prior to php 5.3.6 charset was ignored, and you can use it including options:

$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
// Set options
$options = array(
    PDO::ATTR_PERSISTENT    => true,//can help to improve performance
    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION, //throws exceptions whenever a db error occurs
    PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES uft8'  //>= PHP 5.3.6
);

try {
    $this->conn = new PDO($dsn, $this->user, $this->pass, $options);
}
catch ( PDOException $e ) {

    $this->error = $e->getMessage();
}
Angel M.
  • 2,692
  • 2
  • 32
  • 43