Repeat loop json php mysql

Asked

Viewed 336 times

0

I get a json via php post, and want to insert the information into a table in mysql database..

json{  { "todos": [{ "nome0": "andre", "cor0": "preta" }, { "nome1": "felipe", "cor1": "azul" }, { "nome2": "laura", "cor2": "rosa" } ] }

Php code

<?php
header('Content-Type: text/html; charset=utf-8');
if($_SERVER['REQUEST_METHOD']=='POST')
{
    require_once("dbConnect.php");

    // Definir UTF8

    mysql_set_charset($con, 'utf8');

    $tamanho = $_POST['tamanhoArray'];
    $tamArray = (int)$tamanho;
    $jsonALL = $_POST['todos'];
    $jsonParse = json_decode($jsonALL, true);

    for($i = 0;$i<$tamArray;$i++)
    {


        $sql = "INSERT INTO PEDIDOS (nomeUsuario, corUsuario) VALUES ('$jsonParse->nome.$i','$jsonParse->cor.$i')";

        if(mysqli_query($con,$sql)){

            echo "Usuário cadastrado com sucesso";

        }else{

            echo "Erro ao adicionar usuário";
        }
    }
    mysqli_close($con);


}else{

  echo "Requisição inválida   ";

} 
  • Use the foreach with the $jsonParse, I believe it will make it easier. Also, you can create a separate insertion method, so you better organize your code. Ex. insereRegistro($nome, $cor). And another thing, your JSON is not valid.

  • What’s the problem you’re having?

  • I’m not able to concatenate the $i variable with $jsonParse.

  • @Petruceli. L, is your JSON decoding ? Because the way you went is wrong. The right thing would be: {&#xA; "todos": [{&#xA; "nome1": "andre",&#xA; "cor1": "preta"&#xA; },&#xA; {&#xA; "nome2": "felipe",&#xA; "cor2": "azul"&#xA; },&#xA; {&#xA; "nome3": "laura",&#xA; "cor3": "rosa"&#xA; }&#xA; ]&#xA;}

  • if I put jsonParse->right name1 , but put jsonParse->name. $i not right, records only $i values in the bank

  • RBZ sorry for the way I wrote, but the json is working perfectly. it’s really the way you wrote it. thanks

  • @Petruceli. L your json is still wrong. Use a validator to check. Ex.: https://jsonlint.com/

Show 2 more comments

3 answers

1


Avoid using "nome0", "nome1", "nome2",..., if not you will have infinite properties, and would have to do a "gambiarra" to stay treating your string.

The "nome" would already be a property, so there is no reason to put 0,1,2,3..., because it will only take more work to generate your json to send, and again to the php receive and treat as array.

Basically like this:

<?php

// Seu json
$json = '{
    "todos": [{
        "nome": "andre",
        "cor": "preta"
    }, {
        "nome": "felipe",
        "cor": "azul"
    }, {
        "nome": "laura",
        "cor": "rosa"
    }]
}';

// "Transformando" o json em array
$array = json_decode($json, true);

//echo '<pre>'; // Exibir com pré formatação
//print_r($array);

// Loop no índice "todos"
foreach($array['todos'] as $v){

    // Função para inserir
    insereRegistro($v['nome'],$v['cor'])
}

// Função que recebe as variáveis e insere o registro
private function insereResgistro($nome, $cor) {

    //Seu método para inserir no banco
    $sql = "INSERT INTO PEDIDOS (nomeUsuario, corUsuario) VALUES ('{$nome}','{$cor}')";

    if(mysqli_query($con,$sql))
        echo "Usuário cadastrado com sucesso";
    else
        echo "Erro ao adicionar usuário";

    mysqli_close($con);
}    

?>

-1

// Criando Json
$myArray[] = array("nome"=>"elder", "sobrenome"=>"barbosa", "idade"=>34);
$myArray[] = array("nome"=>"Luanna", "sobrenome"=>"Paz", "idade"=>31);
$myJSON = json_encode(array("usuario"=>$myArray), JSON_UNESCAPED_UNICODE );

echo "MyJson print => ". $myJSON."<br>";// Imprimindo json

// Decodificando o json
$retorno = json_decode($myJSON);
foreach($retorno->usuario as $usuario){
    echo "Nome: ". $usuario->nome."<br>";
}

-1

Try this way.

<?php
header('Content-Type: text/html; charset=utf-8');
if($_SERVER['REQUEST_METHOD']=='POST')
{
    require_once("dbConnect.php");

    // Definir UTF8

    mysql_set_charset($con, 'utf8');

    $tamanho = $_POST['tamanhoArray'];
    $tamArray = (int)$tamanho;
    $jsonALL = $_POST['todos'];
    $jsonParse = json_decode($jsonALL, true);

    for($i = 0;$i<$tamArray;$i++)
    {

        $nome = "nome".$i;
        $cor = "cor".$i;

        $sql = "INSERT INTO PEDIDOS (nomeUsuario, corUsuario) VALUES ('$jsonParse->$nome','$jsonParse->$cor')";

        if(mysqli_query($con,$sql)){

            echo "Usuário cadastrado com sucesso";

        }else{

            echo "Erro ao adicionar usuário";
        }
    }
    mysqli_close($con);


}else{

  echo "Requisição inválida   ";

} 

Browser other questions tagged

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