備忘

PHP MSSQL Driver UTF8 讀取及寫入資料

其實這些語法,在下載回來的套件中都有說明檔解釋的很清楚!但..有時候自己用起來就不是那麼順利!
以下是我自己試出來的部份,用來寫入中文並讀取出來是沒有問題的!
有需要的朋友請參考!

寫入資料的部份
[php]
$serverName = "127.0.0.1";
$connectionInfo = array("Database"=>"test","Uid"=>"sa","Pwd"=>"sa","CharacterSet" => "UTF-8");
//在這個版本,參數多了CharacterSet,可以選定UTF-8內碼
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if ( $conn === false ) {
echo "Could not connect.<br>";
die( print_r( sqlsrv_errors(), true));
}
$tsql1 = "insert into test (test) values(?) ";

$comments ="中文資料";
$data = iconv("utf-8", "utf-16le", $comments);
//在寫入資料時,要使用iconvo做個轉換
echo $comments;

$params1 = array(
array($data,
null,
SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY)
)
);
//官方並建議,sql語法最好都用參數型態來合成,並搭配 SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY來使用把參數內容置入
$stmt1 = sqlsrv_query($conn, $tsql1, $params1);
if ( $stmt1 === false ) {
echo "Error in statement execution.<br>";
die( print_r( sqlsrv_errors(), true));
}
else {
echo "The update was successfully executed.<br>";
}
[/php]

這樣就可以輕鬆的把中文資料寫入SQL了!