0

PHP version: 5.6.28


I got strange issue, that json_encode working not everytime. What I mean:

I have simple connect.php file:

$questions = $con->prepare("
    SELECT Id, Question, Answer1, Answer2, Answer3
    FROM Questions AS q
    ORDER BY RAND()
    LIMIT 1
"); 
$questions->execute();

$questions->bind_result($id, $question, $answer1, $answer2, $answer3);
$questions->store_result();
$questions->fetch();

$qa = array('0' => $id, '1' => $question, '2' => $answer1, '3' => $answer2, '4' => $answer3);

echo json_encode($qa);

This PHP should select 1 random row with Id, question, answer1, answer2 & answer3 from database and later send It to Javascript.

When I refreshing page most of times I got blank page (1/10 it returns data). SQL query working correctly, when testing in phpMyAdmin It always selecting data.

If I'm using var_dump instead of echo json_encode It always selecting data, as expected. So seems that problem is with json_encode.

Data in database are in UTF-8 (included characters like ąčęėįšųūž) so I've also tried echo json_encode($qa, JSON_UNESCAPED_UNICODE); instead of echo json_encode($qa);, but the same problem, nothing changed.

I've also tried to use following function, but result the same:

function raw_json_encode($input, $flags = 0) {
    $fails = implode('|', array_filter(array(
        '\\\\',
        $flags & JSON_HEX_TAG ? 'u003[CE]' : '',
        $flags & JSON_HEX_AMP ? 'u0026' : '',
        $flags & JSON_HEX_APOS ? 'u0027' : '',
        $flags & JSON_HEX_QUOT ? 'u0022' : '',
    )));
    $pattern = "/\\\\(?:(?:$fails)(*SKIP)(*FAIL)|u([0-9a-fA-F]{4}))/";
    $callback = function ($m) {
        return html_entity_decode("&#x$m[1];", ENT_QUOTES, 'UTF-8');
    };
    return preg_replace_callback($pattern, $callback, json_encode($input, $flags));
}  
echo raw_json_encode($qa,JSON_UNESCAPED_UNICODE);

Also I've tried following function, but unsuccessfully too:

function jsonRemoveUnicodeSequences($struct) {
   return preg_replace("/\\\\u([a-f0-9]{4})/e", "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($struct));
}

echo jsonRemoveUnicodeSequences($qa);

Have you any ideas how to solve It?

UPDATE

When I'm using var_dump It returns:

array(4) { ["question"]=> string(32) "Kiek kainuoja �is k?no losjonas?" ["a1"]=> string(10) " 9,99 " ["a2"]=> string(9) " 4,65 " ["a3"]=> string(6) " 15,29" }

echo json_last_error(); returns: 5

And echo json_encode($qa); do not return anything.

Also when I'm checking DEV tools via browser there I see message:

HTML1300: Navigation occurred.

I don't know If It have any relation with my problem.

And first time when I entering website I got following warning:

DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337

And after refresh page this warning disappear.

UPDATE 2

header('Content-Type: text/html;charset=utf-8');
$con = mysqli_connect("localhost","xxxx","xxxx","xxxx");


// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
Infinity
  • 828
  • 4
  • 15
  • 41
  • Can you show us output of `var_dump` when `json_encode` returns nothing? And probably if `json_encode` return nothing - give us the output of `json_last_error()` – vuryss Dec 06 '16 at 16:12
  • @vuryss thank you for attention, I've updated my question with info that you asked. – Infinity Dec 06 '16 at 16:22
  • So you know what's the error - `5`. For others here, it would be good if you describe it as text (error message or constant name) instead of the number. – David Ferenczy Rogožan Dec 06 '16 at 16:26
  • @DawidFerenczy when I',m using `echo json_last_error();` It returns me only number `5`. – Infinity Dec 06 '16 at 16:31
  • @DawidFerenczy I fount at documentation http://php.net/manual/en/function.json-last-error.php that `5` = `JSON_ERROR_UTF8` – Infinity Dec 06 '16 at 16:36
  • 1
    So you have malformed UTF-8 characters in the DB. – vuryss Dec 06 '16 at 16:40
  • Yep, it's pretty clear, some characters in the DB are not valid UTF-8. You can try to plan with `iconv` before you feed the data in `json_encode` or just make sure that the data in the DB are valid. – David Ferenczy Rogožan Dec 06 '16 at 16:41
  • @DawidFerenczy I've tried to use `$qa = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($qa)); echo json_encode($qa);` but It now always returning `""`. – Infinity Dec 06 '16 at 16:44
  • @vuryss In DB it contains characters like 'ąčęėįšųūž', It's lithuanian characters and I need to store them in database table. – Infinity Dec 06 '16 at 16:47
  • Why `utf8_encode`? From the manual: *Encodes an ISO-8859-1 string to UTF-8*. I would use just `$qa` without that function there. Hopefully `iconv` will ignore (remove) broken UTF-8 characters. But it will break your texts anyway, it should just prevent your script from breaking. I would focus on fixing your encoding in the DB at first. – David Ferenczy Rogožan Dec 06 '16 at 16:50
  • @DawidFerenczy Why `utf8_encode` I don't know, I found this sample at google. So what I need to do with my DB? Change collation or what? In DB those characters stored correctly (`ąčęėįšųūž`) and I can't remove those symbols, It will break words. – Infinity Dec 06 '16 at 16:53
  • Can you check the character encoding that your DB Table has ? – vuryss Dec 06 '16 at 16:57
  • @vuryss database collation: `utf8_general_ci`. Each varchar column on `Questions` table in that database have `utf8_general_ci` collation. – Infinity Dec 06 '16 at 17:00
  • Ok then can you show us how you open the connection to the DB? – vuryss Dec 06 '16 at 17:02
  • 2
    Did you set the charset to UTF8 when initializing the connection? http://php.net/manual/en/mysqli.set-charset.php – vuryss Dec 06 '16 at 17:05
  • Thank you for help, that solved me! – Infinity Dec 06 '16 at 17:08
  • Don't do any replace() calls. Don't use iconv(). Do use `JSON_UNESCAPED_UNICODE` -- but that only avoids `\u1234`. Are there any remaining problems? – Rick James Dec 06 '16 at 19:09
  • Collation has **nothing** to do with the encoding. Check what that word means. It's used only for sorting. Check [this my answer](http://stackoverflow.com/a/33220497/971141) for details on the database encoding. There are many things which may cause the encoding to be broken. – David Ferenczy Rogožan Dec 07 '16 at 02:59

0 Answers0