PHP PDO Keep Getting Error: Charset=UTF8 : An inva

2019-08-26 01:55发布

问题:

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..

回答1:

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.



回答2:

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();
}