Procedura: Inviare e recuperare dati UTF-8 con il supporto incorporato di UTF-8

Scarica il driver PHP

Se si usa il driver PDO_SQLSRV, è possibile specificare la codifica tramite l'attributo PDO::SQLSRV_ATTR_ENCODING. Per altre informazioni, vedere Costanti (driver Microsoft per PHP per SQL Server).

Il resto di questo articolo discute la codifica utilizzando il driver SQLSRV, ad eccezione di Inviare stringhe UTF-8 come parametri varchar, che copre entrambi i driver.

Per inviare dati con codifica UTF-8 al server o per recuperarli:

  1. Assicurati che la colonna sorgente o di destinazione sia di tipo nchar o nvarchar. Per le colonne varchar , vedi Inviare stringhe UTF-8 come parametri varchar.

  2. Specificare il tipo di PHP SQLSRV_PHPTYPE_STRING('UTF-8') nella matrice di parametri. In alternativa, specificare "CharacterSet" => "UTF-8" come opzione di connessione.

    Quando si specifica un set di caratteri come parte delle opzioni di connessione, il driver presuppone che le altre stringhe delle opzioni di connessione usino lo stesso set di caratteri. Si presuppone, inoltre, che anche le stringhe di query e nome del server usino tale set di caratteri.

Puoi passare UTF-8, SQLSRV_ENC_UTF8_VARCHAR, o SQLSRV_ENC_CHAR a CharacterSet, ma non puoi passare SQLSRV_ENC_BINARY. La codifica predefinita è SQLSRV_ENC_CHAR. SQLSRV_ENC_UTF8_VARCHAR Richiede la versione 5.14.0 o successiva.

Esempio di connessione

Nell'esempio seguente viene illustrato come inviare e recuperare dati con codificata UTF-8 specificando il set di caratteri UTF-8 quando si effettua la connessione. Nell'esempio viene aggiornata la colonna Comments della tabella Production.ProductReview per un ID revisione specificato. Nell'esempio vengono inoltre recuperati e visualizzati i dati appena aggiornati. Si noti che la colonna Comments è di tipo nvarchar(3850). Si noti inoltre che, prima che vengano inviati al server, i dati vengono convertiti nella codifica UTF-8 usando la funzione PHP utf8_encode. Questa operazione viene eseguita solo per scopi dimostrativi. In uno scenario di applicazione reale, si inizierebbe già con dati con codifica UTF-8.

Nell'esempio si presuppone che SQL Server e il database AdventureWorks siano installati nel computer locale. Quando l'esempio viene eseguito dal browser, tutto l'output viene scritto nel browser.

<?php  
  
// Connect to the local server using Windows Authentication and  
// specify the AdventureWorks database as the database in use.   
//   
$serverName = "<server>";  
$connectionInfo = array( "Database"=>"AdventureWorks", "CharacterSet" => "UTF-8");  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  
  
if ( $conn === false ) {  
   echo "Could not connect.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Set up the Transact-SQL query.  
//   
$tsql1 = "UPDATE Production.ProductReview  
          SET Comments = ?  
          WHERE ProductReviewID = ?";  
  
// Set the parameter values and put them in an array. Note that  
// $comments is converted to UTF-8 encoding with the PHP function  
// utf8_encode to simulate an application that uses UTF-8 encoded data.   
//   
$reviewID = 3;  
$comments = utf8_encode("testing 1, 2, 3, 4.  Testing.");  
$params1 = array(  
                  array( $comments, null ),  
                  array( $reviewID, null )  
                );  
  
// Execute the query.  
//   
$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>";  
}  
  
// Retrieve the newly updated data.  
//   
$tsql2 = "SELECT Comments   
          FROM Production.ProductReview   
          WHERE ProductReviewID = ?";  
  
// Set up the parameter array.  
//   
$params2 = array($reviewID);  
  
// Execute the query.  
//   
$stmt2 = sqlsrv_query($conn, $tsql2, $params2);  
if ( $stmt2 === false ) {  
   echo "Error in statement execution.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Retrieve and display the data.   
//   
if ( sqlsrv_fetch($stmt2) ) {  
   echo "Comments: ";  
   $data = sqlsrv_get_field( $stmt2, 0 );  
   echo $data."<br>";  
}  
else {  
   echo "Error in fetching data.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Free statement and connection resources.  
//   
sqlsrv_free_stmt( $stmt1 );  
sqlsrv_free_stmt( $stmt2 );  
sqlsrv_close( $conn);  
?>  

Per informazioni sull'archiviazione di dati Unicode, vedere Working with Unicode Data (Uso di dati Unicode).

Esempio di colonna

L'esempio seguente è simile al primo, ma anziché specificare il set di caratteri UTF-8 nella connessione, in questo caso si illustra come specificare il set di caratteri UTF-8 nella colonna.

<?php  
  
// Connect to the local server using Windows Authentication and  
// specify the AdventureWorks database as the database in use.   
//   
$serverName = "<server>";  
$connectionInfo = array( "Database"=>"AdventureWorks");  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  
  
if ( $conn === false ) {  
   echo "Could not connect.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Set up the Transact-SQL query.  
//   
$tsql1 = "UPDATE Production.ProductReview  
          SET Comments = ?  
          WHERE ProductReviewID = ?";  
  
// Set the parameter values and put them in an array. Note that  
// $comments is converted to UTF-8 encoding with the PHP function  
// utf8_encode to simulate an application that uses UTF-8 encoded data.   
//   
$reviewID = 3;  
$comments = utf8_encode("testing");  
$params1 = array(  
                  array($comments,  
                        SQLSRV_PARAM_IN,  
                        SQLSRV_PHPTYPE_STRING('UTF-8')  
                  ),  
                  array($reviewID)  
                );  
  
// Execute the query.  
//   
$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>";  
}  
  
// Retrieve the newly updated data.  
//   
$tsql2 = "SELECT Comments   
          FROM Production.ProductReview   
          WHERE ProductReviewID = ?";  
  
// Set up the parameter array.  
//   
$params2 = array($reviewID);  
  
// Execute the query.  
//   
$stmt2 = sqlsrv_query($conn, $tsql2, $params2);  
if ( $stmt2 === false ) {  
   echo "Error in statement execution.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Retrieve and display the data.   
//   
if ( sqlsrv_fetch($stmt2) ) {  
   echo "Comments: ";  
   $data = sqlsrv_get_field($stmt2,   
                            0,   
                            SQLSRV_PHPTYPE_STRING('UTF-8')  
                           );  
   echo $data."<br>";  
}  
else {  
   echo "Error in fetching data.<br>";  
   die( print_r( sqlsrv_errors(), true));  
}  
  
// Free statement and connection resources.  
//   
sqlsrv_free_stmt( $stmt1 );  
sqlsrv_free_stmt( $stmt2 );  
sqlsrv_close( $conn);  
?>  

Invia stringhe UTF-8 come parametri varchar

Con la codifica UTF-8, entrambi i driver inviano un parametro stringa come nvarchar. A partire dalla versione 5.14.0, puoi inviare stringhe UTF-8 come parametri varchar invece. Usa questa opzione quando le tue colonne sono varchar. Quando SQL Server confronta una colonna varchar con un parametro nvarchar, converte il valore della colonna, il che può impedire una ricerca dell'indice.

Ogni driver ha la propria costante. Non usare la costante SQLSRV con PDO_SQLSRV, né la costante PDO_SQLSRV con SQLSRV.

Driver Impostazione Scope
SQLSRV "CharacterSet" => SQLSRV_ENC_UTF8_VARCHAR nelle opzioni di connessione Ogni parametro stringa sulla connessione
SQLSRV SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_UTF8_VARCHAR) nell'array di parametri Un parametro
PDO_SQLSRV PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8_VARCHAR con PDO::setAttribute Ogni parametro stringa sulla connessione
PDO_SQLSRV PDO::SQLSRV_ATTR_ENCODING => PDO::SQLSRV_ENCODING_UTF8_VARCHARnelle opzioni PDO::prepare Una sola istruzione
PDO_SQLSRV PDO::SQLSRV_ENCODING_UTF8_VARCHAR come quinto argomento di PDOStatement::bindParam Un parametro

L'impostazione modifica solo i parametri stringa che non hanno un tipo SQL esplicito. Si applicano le seguenti regole:

  • Un tipo SQL esplicito vince. Ad esempio, SQLSRV_SQLTYPE_NVARCHAR(20) in un array di parametri SQLSRV, o una dichiarazione nvarchar in Dichiarare input string types and lengths (PDO_SQLSRV), continua a inviare nvarchar.
  • Con Always Encrypted, il tipo di parametro proveniente dai metadati di crittografia del server prevale.
  • Una codifica UTF-8 per parametro, SQLSRV_PHPTYPE_STRING('UTF-8') o PDO::SQLSRV_ENCODING_UTF8, invia quel parametro come nvarchar.
  • Le stringhe che leggi vengono restituite in UTF-8, comprese le colonne nchar e nvarchar .

SQL Server converte un parametro varchar nella pagina di codice della collazione predefinita del database. Per inviare caratteri fuori da quella pagina di codice senza perdite, la collazione predefinita del database deve essere una collazione UTF-8, come Latin1_General_100_CI_AS_SC_UTF8, e la colonna di destinazione deve poter memorizzare i caratteri. Una collazione UTF-8 sulla sola colonna non basta. Altrimenti, SQL Server sostituisce i caratteri che la pagina di codice non può rappresentare, tipicamente con un punto interrogativo (?). Per ulteriori informazioni, vedere Supporto per Unicode e regole di confronto.

Con le istruzioni prepare emulate di PDO (PDO::ATTR_EMULATE_PREPARES), PDO_SQLSRV inserisce valori di tipo stringa nel testo della query come valori letterali. Per impostazione predefinita, la codifica varchar UTF-8 produce letterali di caratteri ordinari, che dipendono anch'essi dalle regole di confronto predefinite del database. Un parametro associato a PDO::PARAM_STR | PDO::PARAM_STR_NATL, una connessione con PDO::ATTR_DEFAULT_STR_PARAM impostata a PDO::PARAM_STR_NATL, o un parametro per PDO::SQLSRV_ENCODING_UTF8 parametro produce invece letterali Unicode N'...' .

Esempio di SQLSRV

Il seguente esempio imposta CharacterSet sulla connessione. Legge le impostazioni di connessione dalle variabili di ambiente e fa il backup dal nome del database, dal nome utente e dalla password come descritto in Connessione al server. Crittografa la connessione e convalida il certificato server. Viene utilizzato SQL_VARIANT_PROPERTY per mostrare il tipo che il server riceve. La stringa Zoë esegue un round-trip in un database che utilizza una collazione predefinita Latin1 o UTF-8.

<?php
$config = [];
foreach (['SQL_SERVER', 'SQL_DATABASE', 'SQL_USER', 'SQL_PASSWORD'] as $name) {
    $value = getenv($name);
    if ($value === false || $value === '') {
        throw new RuntimeException("Set $name before running this example.");
    }
    $config[$name] = $value;
}
foreach (['SQL_DATABASE', 'SQL_USER', 'SQL_PASSWORD'] as $name) {
    $config[$name] = '{' . str_replace('}', '}}', $config[$name]) . '}';
}

$conn = sqlsrv_connect($config['SQL_SERVER'], [
    'Database' => $config['SQL_DATABASE'],
    'UID' => $config['SQL_USER'],
    'PWD' => $config['SQL_PASSWORD'],
    'Encrypt' => true,
    'TrustServerCertificate' => false,
    'CharacterSet' => SQLSRV_ENC_UTF8_VARCHAR,
]);
if ($conn === false) {
    die(print_r(sqlsrv_errors(), true));
}

$sql = "SELECT SQL_VARIANT_PROPERTY(?, 'BaseType'), ?";
$stmt = sqlsrv_query($conn, $sql, ['Zoë', 'Zoë']);
if ($stmt === false || sqlsrv_fetch($stmt) !== true) {
    die(print_r(sqlsrv_errors(), true));
}
$type = sqlsrv_get_field($stmt, 0);
$value = sqlsrv_get_field($stmt, 1);
if ($type !== 'varchar' || $value !== 'Zoë') {
    throw new RuntimeException("Unexpected result: $type, $value");
}
echo "Sent as $type: $value\n";
sqlsrv_close($conn);

Esempio di PDO_SQLSRV

Il seguente esempio presuppone una connessione aperta PDO in $conn che utilizza PDO::ERRMODE_EXCEPTION. Per aprirne uno, vedi Connettersi al server. La prima query invia entrambi i parametri come varchar. La seconda query sovrascrive la codifica di un parametro, quindi il server riceve nvarchar.

$conn->setAttribute(PDO::SQLSRV_ATTR_ENCODING, PDO::SQLSRV_ENCODING_UTF8_VARCHAR);

$stmt = $conn->prepare("SELECT SQL_VARIANT_PROPERTY(?, 'BaseType'), ?");
$stmt->execute(['Zoë', 'Zoë']);
[$type, $value] = $stmt->fetch(PDO::FETCH_NUM);
if ($type !== 'varchar' || $value !== 'Zoë') {
    throw new RuntimeException("Unexpected result: $type, $value");
}

$name = 'Zoë';
$stmt = $conn->prepare("SELECT SQL_VARIANT_PROPERTY(?, 'BaseType')");
$stmt->bindParam(1, $name, PDO::PARAM_STR, 0, PDO::SQLSRV_ENCODING_UTF8);
$stmt->execute();
$type = $stmt->fetchColumn();
if ($type !== 'nvarchar') {
    throw new RuntimeException("Unexpected type: $type");
}
echo "Override sent as $type\n";