Save multiple records in the bank

Asked

Viewed 116 times

0

I’m using the following code unsuccessfully.

$conn = mysqli_connect('localhost','user','pass','banco');
    try {

        $body = file_get_contents("php://input");

        $dados = json_decode($body);

        foreach($dados as $dataone){
          $nome = $dataone['nome'];
          $img = $dataone['img'];
          $qtd = $dataone['qtd'];        
        
            $sql = "INSERT into tabela (nome,img,qtd) values ('{$nome}','{$img}','{$qtd}')";
            
            $qr=mysqli_query($conn,$sql);        
      }

  • What is the problem ? Is returning error ? ..

  • You’re not saving

  • Now that I’ve noticed, there’s a simple quotation mark missing here: ({$nome}',

  • That was the problem ?

  • It wasn’t... It’s a json that comes from the APP and saved in the bank, if run out of the is it always saves the last line, nas inside the is not saved anything

  • Friend, put the code of the JSON file that is being sent, without it it becomes difficult to answer your question. The problem here is that you are treating the decoded JSON file as an array, but in fact it is an object with several attributes. You need to know how these attributes are organized in order to be able to write them to the database correctly.

  • @Cloudac, is thus sending to php: { name: "Pedro", img: "images/pedro.png", Qtd: "5"}, { name: "João", img: "images/Joao.png", Qtd: "8"}, { name: "Jose", img: "images/Jose.png", Qtd: "7"}

Show 2 more comments

3 answers

1

See if the script below works, if it doesn’t work, note the error generated and post here in the comments:

<?php
    $conn = mysqli_connect("localhost","user","pass","banco"); // Se não funciona, tente com a linha abaixo
    //$conn = mysqli_connect("localhost","root","pass","banco");
        try {

            $body = file_get_contents("php://input");

            $dados = json_decode($body);

            foreach($dados as $dataone){

                $nome = $dataone['nome'];
                $img = $dataone['img'];
                $qtd = $dataone['qtd'];        

                $sql = "INSERT into tabela (nome,img,qtd) values ('$nome','$img','$qtd')";

                $qr = mysqli_query($conn, $sql);

                if ($qr){
                    echo "Sucesso";
                } else {
                    echo "[ERRO]: " . mysqli_connect_error($conn);
                }               
          }
?>
  • The code being sent to php: { name: "Pedro", img: "images/pedro.png", Qtd: "5"}, { name: "João", img: "images/Joao.png", Qtd: "8"}, { name: "Jose", img: "images/Jose.png", Qtd: "7"}

0


Next, I believe that first, the JSON file itself that is being sent to the php server contains errors, check again the JSON code that is being sent and compare with what I will post. JSON file that should be sent to the PHP server:

{
    "pessoas": 
    [
        {   "nome": "Pedro", 
            "img": "images/pedro.png", 
            "qtd": "5"
        }, 
        {   "nome": "João",
            "img": "images/joao.png",
            "qtd": "8"
        }, 
        {   "nome": "Jose",
            "img": "images/jose.png",
            "qtd": "7"
        }
    ]
}

PHP script to insert JSON file data into the database:

<?php
    $conn = mysqli_connect("localhost","user","pass","banco");

        try {

            $body = file_get_contents("php://input");

            $dados = json_decode($body);

            for($i = 0; $i < count($dados->pessoas), $i++){

                $nome = $dados->pessoas[$i]->nome;
                $img = $dados->pessoas[$i]->img;
                $qtd = $dados->pessoas[$i]->qtd;

                $sql = "INSERT into tabela (nome,img,qtd) values ('$nome','$img','$qtd')";

                $query = mysqli_query($conn, $sql);

                if ($query){
                    echo "Dados inseridos no banco com Sucesso";
                } else {
                    echo "Houve um erro enquanto tentava inserir dados no banco : " . mysqli_connect_error($conn);
                }   
            }

          }
?>

0

Note: my table with latin1_general_ci

This is not my thing, but I did a test and only succeeded by making these changes:

On the page I used:

<meta charset="utf-8" />

The code sent to php with the following syntax:

$body = '[{ "nome": "Pedro", "img": "images/pedro.png", "qtd": "5"}, { "nome": "João", "img": "images/joao.png", "qtd": "8"}, { "nome": "Jose", "img": "images/jose.png", "qtd": "7"}]';

Accented letters cause errors (John), I used utf8_encode.

utf8_encode - decodes a string in the ISO-8859-1 standard for utf-8.

$body = utf8_encode ($body);

and I finally used:

$dados = json_decode($body,true);

json_decode parses the JSON encoded string and converts it into a PHP variable, when TRUE, the return will be converted to associative array.

Browser other questions tagged

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