简体   繁体   中英

How can I return the keys from fetch_assoc as strings so that the array can be valid JSON data? (PHP / mysqli)

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" } }

Things may be getting hung up on the Unicode text; try modifying your database code as follows:

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[] = array_map("utf8_encode", $row);
        }
        return $rows;
    } else {
        return mysqli_error($conn);
    }
}

(By the way, you're introducing a lot of overhead by reconnecting to the database with every query.)

You can simply get the keys by looping the fetched array

    while($row = $result->fetch_assoc()) { //each row
      foreach($row as $key => $value){ // each key in each row
        echo $key;
      }
    }

Like this ?

while($row = $result->fetch_array(MYSQL_ASSOC)) {
  $rows [] = $row;
}
echo json_encode($rows);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM