Here's my function:
<?php
function getResults($query) {
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($query);
if ($result) {
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
} else {
return mysqli_error($conn);
}
}
?>
And I use it here:
if ($_POST["action"] == "getCitiesByState") {
$cities = getResults("SELECT * FROM tbl_cidades WHERE estado_id = ".$_POST["state_id"]);
echo json_encode($cities, JSON_UNESCAPED_UNICODE);
die();
}
It outputs:
{id: "8853", estado_id: "26", nome: "Adamantina", cep: "17800000", loc_no_abrev: "Adamantina"},…]
The id, estado_id, nome, etc, all unquoted, form invalid JSON data. How can I return them as strings so that they can be valid JSON?
Here's one example of the output of var_dump($cities)
array(1) { [0]=> array(5) { ["id"]=> string(4) "1778" ["estado_id"]=> string(1) "7" ["nome"]=> string(9) "Brasília" ["cep"]=> string(0) "" ["loc_no_abrev"]=> string(9) "Brasília" } }