Categories
Database PHP Programming

PHP: sqlsrv problems with UTF-8 values? Set your CharacterSet option!

Are you banging your head trying to figure out how to convert a seemingly invalid UTF-8 value into a valid one? You might be surprised to know that the problem isn’t how PHP interprets the characters, but rather a database connection issue. If the UTF-8 value in question looks valid in the database but does not look right when displayed on a web page, that could mean your database connection settings are not set correctly.

In PHP’s sqlsrv_connect page, the function lists connectionInfo as being an optional parameter. One of the connectionInfo option is the CharacterSet, which is set to value SQLSRV_ENC_CHAR by default. What you want to do is set the CharacterSet value to UTF-8. See how easy that was? Your UTF-8 problems should be solved.

$result = sqlsrv_connect($hostname, array(
	'UID' => $username,
	'PWD' => $password,
	'Database' => $database,
	'ConnectionPooling' => ($pooling) ? 1 : 0,
	"CharacterSet" => "UTF-8"	// <---- voila
));

For more SQLSRV Connection options, go here.

2 replies on “PHP: sqlsrv problems with UTF-8 values? Set your CharacterSet option!”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s