Search code examples
phpmysqlspecial-characters

Special characters in column names


I got a database from a customer and need to create some logic around it, like reading and inserting entries.

When I tried some basic requests, like:

$json = array ();
$query = "select * from tab1";

if ($result = $link->query ( $query )) {
    while ( $row = $result->fetch_assoc () ) {
        array_push ( $json, $row );
    }
}

die ( json_encode ( $json ) );

I surprisingly got an empty response.

Executing the same query directly from PHPMyAdmin, I got all expected results.

When I just dumped the JSON result in the browser, I noticed (extract):

... string(30) "ColumnName(�)"  ...

It took me a while to find out, that there were columns name with some special charaters, like µ and °. Apparently, they could not be displayed properly so the whole response became invalid and I got no results.

Just removing those characters from the column name solved the problem.

Is there another solution, instead of just manually looking for those characters and removing them?


Solution

  • Because json_encode()/json_decode() deals only with UTF-8 encoding, you must convert all non utf8 encoded string to utf-8

    You can use utf8-encode() function