PHP: json_encode() doesn't show anything with multidimensional array

允我心安 提交于 2021-01-28 19:32:32

问题


I'm trying to make a simple PHP script that fetches a table from my MySQL database and encodes the results in JSON, so I can use them later in Java.

This is my code:

<?php
    $servername = "localhost:3036";
    $username = "example_user";
    $password = "example_password";

    $conn = mysql_connect($servername, $username, $password);

    if(! $conn) {
        die("Could not connect: " . mysql_error());
    }

    $sql = "SELECT * FROM table_name";
    mysql_select_db("database_name");
    $retval = mysql_query($sql, $conn);

    if(! $retval) {
        die("Could not get data: " . mysql_error());
    }

    while($row = mysql_fetch_assoc($retval)) {
        $output[]=$row;
    }

    print(json_encode($output));
    mysql_close($conn);
?>

This just gives a blank page as output (error messages are set to display). However, if I change json_encode($output) to json_encode($output[0]) (or any other number within the array's bounds), the output becomes that one $row array.

This is probably a really stupid question, but after about 3 hours of research I'm at my wit's end. Thank you for any help.


回答1:


User @Joni led me to the solution.

Adding mysql_set_charset("utf8") fixed my issue.

As mentioned in this post: Why is this PHP call to json_encode silently failing - inability to handle single quotes?.




回答2:


Try

 echo json_encode($output) ;



回答3:


It seems you have some utf8 character in your result set

add this statement before running your query

mysql_query('SET CHARACTER SET utf8');



回答4:


Update

"mysql"

to

"mysqli"

and add

mysqli_set_charset($variável_de _conexão, 'utf8');

below the connection variable



来源:https://stackoverflow.com/questions/39140174/php-json-encode-doesnt-show-anything-with-multidimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!