Pass SQL output to JSON

Asked

Viewed 658 times

6

Hello, I want to pass the result of a select to json, but I can’t check why I can’t see it.

So someone could tell me why this code doesn’t print anything?

include_once 'conexao.php';

$query = "SELECT client_id, name, email FROM client";
$result = $dbcon->query($query);
$rows = array();    
while($row = mysqli_fetch_assoc($result)) {    
        $rows[] = $row;
}

echo json_encode($rows);

Result of var_dump($rows):

array(8) {
    [0]=> array(3) {
        ["client_id"]=> string(1) "1"
        ["name"]=> string(26) "Fernanda Neri Duarte Silva"
        ["email"]=> string(18) "[email protected]"
    }
    [1]=> array(3) {
        ["client_id"]=> string(1) "2"
        ["name"]=> string(36) "Elaine Cristina Gon�alves Durvalino "
        ["email"]=> string(16) "[email protected]"
    } 

3 answers

2

Try to change your content while to the following:

while($row = mysqli_fetch_assoc($result)) {    
  $vclientid = $row['client_id'];
  $vname = $row['name'];
  $vemail = $row['email'];

  $rows['client'][] = array('client_id' => $vclientid, 'name' => $vname, 'email' => $vemail);
}

1

Try to do so:

$array[0] =  array('jujuba', 'bola', 'cachorro');
$array[1] =  array('carro', 'da like', 'em mim o/');

echo "<pre>";
var_dump($array);

var_dump(json_encode($array, JSON_FORCE_OBJECT));

Add the parameter JSON_FORCE_OBJECT

Comparing results:

// Sem JSON_FORCE_OBJECT
string(63) "[["jujuba","bola","cachorro"],["carro","da like","em mim o\/"]]"

// com JSON_FORCE_OBJECT    
string(95) "{"0":{"0":"jujuba","1":"bola","2":"cachorro"},"1":{"0":"carro","1":"da like","2":"em mim o\/"}}"

I made a class (still improving) that debugs if, want to take a look www.bulfaitelo.com.br/2016/11/debug-variables-e-classes-with-o.html

1

I found the answer. The problem was accents. I had to encode to UTF-8 to be able to solve.

The resolution was even a little simple. See:

**

$query = "SELECT client_id, name, email FROM `client`";
$result = $dbcon->query($query);
$myArray = array(); 
while($fetch = $result->fetch_assoc()) {        
    $myArray[] = array("client_id" => utf8_encode($fetch['client_id']), "name" => utf8_encode($fetch['name']), "email" => utf8_encode($fetch['email']));        
}


$json = json_encode($myArray);
echo $json;**

Browser other questions tagged

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