如何通过PHP从mssql数据库传递特殊字符

时间:2015-06-01 23:25:05

标签: php android sql-server json

我有这个代码工作正常我的应用程序使用json获取数据并且一切正常但是当我插入特殊字符,如ñ我需要得到我不能被告知我应该使用utf8_encode但我不知道如何在此处应用它。

<?php
    require_once(dirname(__FILE__).'/ConnectionInfo.php');


    //Set up our connection
    $connectionInfo = new ConnectionInfo();
    $connectionInfo->GetConnection();

    if (!$connectionInfo->conn)
    {
        //Connection failed
        echo 'No Connection';
    }

    else
    {
        if (isset($_POST['mod']) && isset($_POST['lec']) && isset($_POST['clase']))
        {   
        $mod = $_POST['mod'];
        $lec = $_POST['lec'];
        $clase = $_POST['clase'];
        //Create query to retrieve all contacts
        $query = 'SELECT TituloEjercicio,PreguntaEjercicio,Opcion1Ejercicio,Opcion2Ejercicio,Opcion3Ejercicio,Opcion4Ejercicio,EstaCorrectaEjercicio FROM ejercicios WHERE QueModulo = ? and QueLeccion = ? and Queclase = ?';
        $params = array($mod,$lec,$clase);      
        $stmt = sqlsrv_query($connectionInfo->conn, $query,$params);

        if (!$stmt)
        {
            //Query failed
            echo 'Query failed';
        }
        else
        {
            $contacts = array(); //Create an array to hold all of the contacts
            //Query successful, begin putting each contact into an array of contacts

            while ($row = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC)) //While there are still contacts
            {
                //Create an associative array to hold the current contact
                //the names must match exactly the property names in the contact class in our C# code.
                $contact = array("lbl_variable_cuestionario_titulo" => $row['TituloEjercicio'],
                                 "lbl_variable_pregunta" => $row['PreguntaEjercicio'],
                                 "opcion1" => $row['Opcion1Ejercicio'],
                                 "opcion2" => $row['Opcion2Ejercicio'],
                                 "opcion3" => $row['Opcion3Ejercicio'],
                                 "opcion4" => $row['Opcion4Ejercicio'],
                                 "EstaCorrecta" => $row['EstaCorrectaEjercicio']
                                 );                                          
                //Add the contact to the contacts array
                array_push($contacts, $contact);
            }

            //Echo out the contacts array in JSON format
            echo json_encode($contacts);
            sqlsrv_close($connectionInfo->conn);
        }
        }
        sqlsrv_close($connectionInfo->conn);
    }
    sqlsrv_close($connectionInfo->conn);
?>

1 个答案:

答案 0 :(得分:0)

如果您的问题在于将非拉丁字符推送到MySQL,那么您可能只需要将数据库配置为使用UTF8。有很好的tutorials online可以告诉你如何做到这一点。