Problems to return json from MySQL database

I’m having problems to return json from MySQL database, when I print_r(array), the array that was returned from the query, it shows the data but when I try to convert it to json it shows nothing. I tested with xaamp and it works fine. I am using Insomnia to test GET requests.

$DB_HOST = 'sql207.epizy.com';
$DB_USER = 'epiz_25831176';
$DB_PASSWORD = 'Hidden';
$DB_NAME = 'epiz_25831176_hidden';

class DBI {

    public static $connection;

    public static function executeSQL(){

        $myArray = array();

     

        if($result = mysqli_query(DBI::$connection, "SELECT * FROM test")){

            echo "Query was executed! \n";

            if(mysqli_num_rows($result) > 0){

                echo "Number of rows is greater than 0 \n";

                

                while($row = mysqli_fetch_assoc($result)){

                    $myArray[] = $row;

                }

                        

            } else {

                echo "Number os rows is equal to 0 \n";

            }

        } else {

            echo "Failed to execute the query! \n";

        }

        print_r($myArray);

        return $myArray;

    }

}

DBI::$connection = mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME);

if(!DBI::$connection){

    echo "Connection failed: ".mysqli_connect_error(). "\n";

} else {

    echo "Connected to MySQL \n";

}

$myArray = DBI::executeSQL();

header('Content-Type: application/json');
        echo json_encode($myArray, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

So… what makes you think that this is a hosting issue? If a print_r shows the data, but a json_encode does not, then probably the input data or flag set is invalid, or maybe the fact that you’re sending data before sending the content type header crashes the PHP script.

PHP json_encode is PHP json_encode. We didn’t do anything special with that function that could cause it to behave special in any way.

3 Likes

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.