Import json file to a Mysql database?

Asked

Viewed 1,527 times

1

Well I am started in the database study and I came across the following situation have this json file with the following data:

[{"nome":"José","ddd":27,"telefone":21239990,"cpf":"11111111111","sabe_programar":true},{"nome":"João","ddd":27,"telefone":21239990,"cpf":"22222222222","sabe_programar":false},{"nome":"Maria","ddd":27,"telefone":21239990,"cpf":"22222222222","sabe_programar":true},{"nome":"Antônio","ddd":27,"telefone":21239990,"cpf":"22222222222","sabe_programar":false}]

Well I already managed to pass it to php, with this code:

<?php
$arquivo = file_get_contents('pessoas.json');
$json = json_decode($arquivo);
foreach($json as $registro):
    echo 'nome: ' . $registro->nome . ' - ddd: ' . $registro->ddd . ' - telefone: ' . $registro->telefone . ' - cpf '. $registro->cpf . ' - sabe_programar' . $registro->sabe_programar . '<br>';
endforeach;

My doubt is how do I now import this data into a Mysql database? (I have already created a database, and a table)

  • Like this keeping the proportions of each language? https://answall.com/a/236529/64969

1 answer

2


Hello! Then, do the following, transform Json to array and play the dice from each table to a separate array:

$meu_array = json_decode($var_do_jason, true);
$n = $meu_array["nome"];
$c = $meu_array["cpf"];
$r = $meu_array["rg"]; 

Then use a for to insert the elements into the base:

for(i=0;$meu_array>i;i++){
$nome = $n[i];
$cpf = $c[i];
$rg = $r[i];
            mysql_query("INSERT INTO tabela (nome, cpf, rpg) VALUES('$nome', '$cpf', '$rg'"));

        }
  • And how I connect to the bank?

  • 1

    In this case, you have to study more about PHP and Mysql (even to avoid sql Injection etc). I suggest these two: http://www.devmedia.com.br/php-pdo-se-connecter-ao-banco-dados/37211 http://rberaldo.com.br/pdo-mysql/

Browser other questions tagged

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