0

I'm using slim in my rest api, this is a get method. When it is echoed the json array is empty.

$app->get("/users", function () {

$response = array();
$db = new DbHandler();

// fetching all users
$result = $db->getAllUsers();

$response["error"] = false;
$response["users"] = array();

// looping through result and preparing users array
while ($user = $result->fetch_assoc()) {
    $tmp = array();
    $tmp["id_user"] = $user["id_user"];
    $tmp["name"] = $user["name"];
    array_push($response["users"], $tmp);
}
//var_dump($tmp);
//var_dump($response);

echoRespnse(200, $response);
});

The var_dump show me perfectly the array, the problem is in the json_encode

EDIT: here is the code of the echoResponse

function echoRespnse($status_code, $response) {
    $app = \Slim\Slim::getInstance();
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

EDIT 2: the var_dump of the $response

array(2) {
  ["error"]=>
  bool(false)
  ["users"]=>
  array(8) {
    [0]=>
    array(2) {
      ["id_user"]=>
      int(1)
      ["name"]=>
      string(14) "Pedro Gonzalez"
    }
    [1]=>
    array(2) {
      ["id_user"]=>
      int(2)
      ["name"]=>
      string(14) "Juan Marcano"
    }
    [2]=>
    array(2) {
      ["id_user"]=>
      int(3)
      ["name"]=>
      string(12) "Ana Maria"
    }
    [3]=>
    array(2) {
      ["id_user"]=>
      int(4)
      ["name"]=>
      string(13) "Eduado Perez"
    }
    [4]=>
    array(2) {
      ["id_user"]=>
      int(5)
      ["name"]=>
      string(12) "Gilberto Perez"
    }
    [5]=>
    array(2) {
      ["id_user"]=>
      int(6)
      ["name"]=>
      string(12) "Roberto Perez"
    }
    [6]=>
    array(2) {
      ["id_user"]=>
      int(7)
      ["name"]=>
      string(12) "Juan Perez"
    }
    [7]=>
    array(2) {
      ["id_user"]=>
      int(8)
      ["name"]=>
      string(15) "Juanito Alimaña"
    }
  }
}

EDIT 3: I've solved the problem. Was something about the charset of the database, i've added this code to my connect function and its work now like a charm.

function connect() {
    include_once dirname(__FILE__) . './Config.php';

    // Connecting to mysql database
    $this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

    // magic trick
    if (!$this->conn->set_charset("utf8")) {
         printf("Error cargando el conjunto de caracteres utf8: %s\n", $mysqli->error);
         exit();
    } else {
         printf("Conjunto de caracteres actual: %s\n", $this->conn->character_set_name());
    }

    // Check for database connection error
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    // returing connection resource
    return $this->conn;
}
Rorschach
  • 31
  • 9

0 Answers0