7

I using ODBC to connect sql server 2008 like

$virtual_dsn = 'DRIVER={SQL Server};SERVER=MyServerName;DATABASE=myDatabase';
$conn = odbc_connect($virtual_dsn,'sa','mypass') or die('ODBC Error:: '.odbc_error().' :: '.odbc_errormsg().' :: '.$virtual_dsn);

if (!$conn){
    if (phpversion() < '4.0'){
      exit("Connection Failed: . $php_errormsg" );
    }
    else{
      exit("Connection Failed:" . odbc_errormsg() );
    }
}

// This query generates a result set with one record in it.
$sql="SELECT TOP 10 * FROM Mytable";

# Execute the statement.
$rs=odbc_exec($conn,$sql);

// Fetch and display the result set value.
if (!$rs){
    exit("Error in SQL");
}
while (odbc_fetch_row($rs)){


    $col1=odbc_result($rs, "name");
    echo "$col1 <br>";

}

// Disconnect the database from the database handle.
odbc_close($conn);

But i get text not correct like

b?�o c?�o việc sử dụng

i try to using odbc_exec($conn, "SET names utf8"); but get error

 Warning: odbc_exec(): SQL error: [Microsoft][SQL Server Native Client 10.0][SQL Server]'names' is not a recognized SET option., SQL state 37000 in SQLExecDirect in C:\xampp\htdocs\sql\index.php on line 32

How set utf-8 using odbc_connect thanks

DeLe
  • 2,442
  • 19
  • 88
  • 133
  • Is this output to a web browser? Did you set the correct charset in the output `Content-type`? http://stackoverflow.com/questions/905173/how-do-i-set-character-encoding-to-utf-8-for-default-html – Michael Berkowski Sep 11 '13 at 01:52
  • See also http://stackoverflow.com/questions/16812943/character-set-issue-usiing-sql-server-and-odbc-in-php – Michael Berkowski Sep 11 '13 at 01:55
  • @MichaelBerkowski I have `header("Content-Type: text/html; charset=utf-8");` on top but not working and using `iconv("Windows-1256", "UTF-8", "$col1")` that still not working? My column has `Collation: SQL_Latin1_General_CP1_CI_AS, nvarchar(3000)` ? – DeLe Sep 11 '13 at 02:01
  • This may have already answered your question: [How to set charset for SQL Connection][1] [1]: http://stackoverflow.com/questions/1322421/php-sql-server-how-to-set-charset-for-connection – Farhan Javed Mar 24 '14 at 01:10

1 Answers1

3

odbc_exec doesn't accept 'SET NAMES utf8' as second parameter. the second parameter must be the query.

to set utf8 for variables only use utf8_decode or iconv

$col1=utf8_decode(odbc_result($rs, "name"));

or

$col1=odbc_result($rs, "name");
iconv("UTF-8", "CP1252", $col1);

and

Warning: odbc_exec(): SQL error: [Microsoft][SQL Server Native Client 10.0][SQL Server]'names' is not a recognized SET option., SQL state 37000 in SQLExecDirect in C:\xampp\htdocs\sql\index.php on line 32

this is not an error, is a WARNING. but check odbc_exec manual to ensure all.

Néstor
  • 570
  • 2
  • 8
  • 22