php array for json will not all data

Asked

Viewed 105 times

-2

Hi, I’m having a problem with my code and I wanted your help.

I need to take data from a table and send it as json, I have 10 items in my table but json only sends one.

Table: local

inserir a descrição da imagem aqui

In my code where I put all PHP and Msqli

include("connect.php");

header("Content-Type: application/json");

$queryString =  "SELECT * FROM `local`";   

$query = mysqli_query($conexao, $queryString) or die(mysqli_error());

$paises = array();

while ($pais = mysqli_fetch_assoc($query)) {

    $paises['paises'] = $pais['paises'];

}

echo json_encode($paises);

And he only returns me the last item that is "Argentina" and it was the most that I could because I have tried several ways. If you can help me there I appreciate.

  • Display the json array result with a print_r() to see what is being displayed. print_r(json_encode($paises));

2 answers

0

Come back like this:

$paises = array();
//EDIÇÃO  while ($pais = mysqli_fetch_assoc($conn, $query)) {
while ($pais = mysqli_fetch_assoc($query)) {

    $paises[] = array(
        "paises" => $pais['paises'];
    );

}

echo json_encode($paises);

Because the way you’re sending is just replacing the value.

  • The parentheses of the array. And why not use the function mysqli_fetch_all?

  • Unfortunately it didn’t work out it keeps getting a value in json. and Anderson how could use this mysqli_fetch_all?

  • @Marlonyago maybe didn’t work because @adventistaam put a parameter $conn the most in the function call. Keep only the parameter $query as you asked in the question. About the mysqli_fetch_all, see the documentation.

  • @Andersoncarloswoss is correct. That’s right.

  • it is also recommended that mysqli_error has the connection mysqli_error($connection)

-1

Thank you all, I managed to solve the problem

$paises = array();

while ($pais = mysqli_fetch_assoc($query)) {

$paises[] = $pais['paises'];

}

echo json_encode($paises);

And I changed the DB that was the main problem

  • 1

    The answer is basically the same as the other one, so why post it again? If the answer was useful to you, vote positively and mark it using the icon on the left side of the answer. For more information, do the [tour].

Browser other questions tagged

You are not signed in. Login or sign up in order to post.