Consume JSON data from Mysql PHP flock

Asked

Viewed 239 times

2

I created in my MYSQL 3 fields ID, Cliente, Produtos where they are registered via JSON the information of Cliente and the produtos that he selected.

JSON Client

{
     "nomecliente":"Cristiano",
     "email":"[email protected]",
     "telefone":"16991337891",
     "mensagem":"rerwerewrwerewr" 
}   

JSON Produto

[
  {
     "nome":"Samsung ali",
     "quantidade":1
  },{
     "nome":"notebook hp",
     "quantidade":1
  }
]

How can I display this return on PHP?

  • How do you retrieve this information in the bank, theoretically json_decode resolves

2 answers

1

just use the json_decode();

$retorno = json_decode($o_seu_Json);

$retornoAssociativo = json_decode($o_seu_Json,true); //a boolean true no parametro transforma a array em uma array associativa

But make sure that the value is encoded in UTF-8, or you have to pass the constant JSON_INVALID_UTF8_IGNORE but only if yours PHP is higher than version 7.2

More information here Documentation json_decode();

  • Thank you for the answer, but it didn’t happen, so can you take a look? while($msgn = mysqli_fetch_assoc($query)){ $retorno = json_decode($msgn['cliente']); } echo $retornoAssociativo = json_decode($msgn,true);

  • where $msgn['client'] is the field where you have customer data

  • ok look your code is wrong for some reasons while that way your variable $return will always be subscribed that way ie for each cycle your $return will not equal to = 1,2,3,4,5,6 but simply = to 6

  • do this in your code to understand what is happening while($msgn = mysqli_fetch_assoc($query)){ var_dump(json_decode($msgn['cliente'])); }

  • Object(stdClass)#4 (4) { ["client name"]=> string(9) "Cristiano" ["email"]=> string(25) "[email protected]" ["phone"]=> string(11) "16991337891" ["message"]=> string(15) "rerwerewrwerewr" } Object(stdClass)#4 (4) { ["client name"]=> string(9) "Cristiano" ["email"]=> string(25) "[email protected]" ["phone"]=> string(11) "16991337891" ["message"]=> string(14) "test message" }

  • 1

    while($msgn = mysqli_fetch_assoc($query)){ $retorno[] =json_decode($msgn['cliente'])); }print_r($retorno); will print you all elements of the created array now or within the loop the $retorno[] will always add a new object to each iteration

  • to access the first person $return[0], if you want the name of the first person $return[0]["client name"] etc

  • Fatal error: Uncaught Error: Cannot use Object of type stdClass as array in C: xampp htdocs cart received.php:78 Stack trace: #0 {main} thrown in C: xampp htdocs cart received.php on line 78 ------------------- my code ----------------- echo $return[0]["client name"];

  • was because you didn’t use the second parameter as I indicated above

  • @Cristianofacirolli indicate that the reply was accepted pff or I will continue to receive notifications ahah

Show 6 more comments

0

// string json vai receber os dados do cliente no formato json

 $json_str = '{
    "nomecliente":"Cristiano",
    "email":"[email protected]",
    "telefone":"16991337891",
    "mensagem":"rerwerewrwerewr" 
  }';

// faz o parsing na string e gera um obj php
$obj = json_decode($json_str);
//imprime o conteúdo do objeto 
echo "Nome: $obj->nomecliente<br>";
echo "Email: $obj->email<br>";
echo "Tel: $obj->telefone<br>";
echo "Msg: $obj->mensagem<br>";

In the case of json Product that contains more than one record, you would have to represent this multiple json object using an array, example:

 // Você tem esse json com 2 elementos:

 {
    produtos: [
        {"nome":"Samsung ali", "quantidade": 1},
        {"nome":"notebook hp", "quantidade": 1}
    ]
 };

 // string json "um array com 2 elementos" ficaria assim

 $json_str = '{"produtos": '. '[
    {"nome":"Samsung ali", "quantidade": '. 1 .'},'.
    '{"nome":"notebook hp", "quantidade": '. 1 .'}'.                
']}';

// faz o parsing da string, criando o array "produtos"
$jsonObj = json_decode($json_str);
$produtos = $jsonObj->produtos;

// agora é só percorrer o array, imprimindo cada produto
foreach ( $produtos as $product ) {
    echo "Nome: $product->nome <br> Quantidade: $product->quantidade<br>"; 
  }

RESOLUTION

    $lista = "SELECT * FROM contato ORDER BY data_msg DESC";
    $query = mysqli_query($conexao, $lista) or die(mysqli_error());

    // tenha certeza q esta vindo obj php e n json e tente:
    while($result = mysqli_fetch_assoc($query)){ 
       $retorno[] = array_map('utf8_encode', $result);
    }
    echo json_encode($retorno);
   // com essa linha acima você tem um obj json

Otherwise json_decode resolves.

  • Thank you for the answer, but is it something like that? $list = "SELECT * FROM contact ORDER BY data_msg DESC"; $query = mysqli_query($connected, $list) or die(mysqli_error()); $q = array(); while ($td = mysqli_fetch_assoc($query)) {$q[] = $td['client'];} $data = json_encode($q)echo"Name: $data->client name<br>";

  • am having the following return string(117) "{"customer name":"Cristiano","email":"[email protected]","phone":"16991337891","message":"rerwerewrwerewr"}"

  • if I try this while ($td = mysqli_fetch_assoc($query)) { $q[] = $td['client']; } var_dump(json_decode($q)); it returns me with error Warning: json_decode() expects Parameter 1 to be string, array Given in C: xampp htdocs cart received.php on line 78 NULL

  • msg says q must see a string of $q when you do json_decode($q), because it is an associative matrix q has several fields, so try: while ($td = mysqli_fetch_assoc($query)) { $data = $td['client']; } $json = json_decode($data); ($json as $item){ foreach($item as $i){ echo $i; } }

  • Warning: Invalid argument supplied for foreach() in C: xampp htdocs cart received.php on line 77

Browser other questions tagged

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