TaneMahuta
TaneMahuta

Reputation: 367

PHP / MySQL: Certain characters not being encoded properly and appearing as question marks

I am new to PHP and MySQL and hope someone can help me with this.

I have a MySQL db with a table called "myTable".

Both the server connection collation and the single columns containing text are set up with the data type "utf8_general_ci" and all characters appear correctly within the db.

However, when I use PHP to fetch (select) data from this table and echo it out on my page the browser shows question marks instead of certain non-English characters.

E.g. occuring with the German characters ä, ö, ü (i.e. the a, o and u with two dots above them). Example: The German term "Geschützter Bereich" (en: Restricted Area) appears as "Gesch?tzter Bereich".

I currently use the following to select the data so my guess is I either need to apply proper (utf-8) encoding again when selecting it OR when echoing it to the page but don't know how to achieve this here.

I found that PHP has the following and other encoding options but was wondering if there is a way that I can set this just once on a page instead of all the time I am echoing something out:

string utf8_encode ( string $data )

Can someone tell me the proper way to do this ?
I am mainly interested in standard European languages like German, French, Spanish etc. and currently do NOT have to cover Asian languages and Hebrew.

My current code:

    $tbl = "myTable";
    $lang = $_GET["lang"];
        if(!isset($lang)){
            $lang = "de";
        }

    // fetch db data
    $conn = new mysqli($servername, $username, $password, $dbname);
    if($conn->connect_error){
        die("Connection failed: " . $conn->connect_error);
    } 
    $sql = "SELECT * FROM " . $tbl;
    $result = $conn->query($sql);

    // store data in temporary array 
    while($translations = $result->fetch_assoc()){
        $arr[] = array("ID" => $translations["tID"], "trans" => $translations[$lang]);
    }
    $conn->close();

    // get required items from array
    function fetchByID($arr, $itemID){
        foreach($arr as $key => $val){
            if($val["ID"] == $itemID){
                echo $val["trans"];
            }
        }
    }

And to echo it out:

echo fetchByID($arr, 1); ...

Many thanks in advance.

Upvotes: 2

Views: 112

Answers (1)

NIRANJAN S.
NIRANJAN S.

Reputation: 317

Please specify the character set by adding

$conn->set_charset("utf8") 

Upvotes: 3

Related Questions