Pergunta

I have the following column in my database with UTF-8 encoded letters:

  • chineseWords

    nǐ hǎo

console.log(value) gives: null


If I change them to non UTF-8,

  • chineseWords

    ni hao

console.log(value) gives: ni hao


If I just keep one word

  • chineseWords

console.log(value) gives: n?


jQuery:

function getData (functionToRun) {  
    $.getJSON("phpscripts.php", {"_functionToRun" : functionToRun},
        function (returned_data) {                      
            var value = returned_data.chineseWords;         
            console.log(value);
        }
    );
}

PHP:

$qry = 
    'SELECT * 
    FROM tasks
    WHERE npc_id_fk = 1';

$result = $mysqli->query($qry) or die(mysqli_error($mysqli));

while ($row = $result->fetch_assoc()) {
    echo json_encode($row);
}   

Why would the browser be outputting null and n??


EDIT: following this blog on encoding and decoding UTF-8, I tried:

console.log(decodeURIComponent(value)); //output: n?


EDIT 2:

Connect:

<?php 
$mysqli = new mysqli("localhost", "root", "", "my_db");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (Error code: " . $mysqli->connect_errno . ")... " . $mysqli->connect_error;
}
?>

Start of my phpscripts.php file:

<?php
include 'runDB.php';
mysql_set_charset($mysqli, "utf8");

index.php:

<!DOCTYPE html>
<html>
    <head>
        <title>Playground</title>
        <meta charset="UTF-8">
Foi útil?

Solução

In your HTML Header add:

<meta charset="UTF-8">

In your PHP Mysql call add:

mysql_set_charset('utf8',$connectToDBVar);

after your db mysql_connect but before your query

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top