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();
}