Pass SQL result to JSON

6

Hello, I want to pass the result from a select to json, but I can not see why I can not see it.

So could anyone tell me why this code does not 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]"
    } 
    
asked by anonymous 03.11.2016 / 23:57

3 answers

2

Try changing the contents of your 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);
}
    
04.11.2016 / 06:15
1

Try to do this:

$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 so fine) that debug itself, you want to have a look www.bulfaitelo.com.br/2016/11/debugar- variables-and-classes-with-o.html

    
04.11.2016 / 09:42
1

I found the answer. The problem was the accents. I had to encode to UTF-8 to get it resolved.

The resolution was even a bit 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;**
    
04.11.2016 / 12:01