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.– rbz
What’s the problem you’re having?
– Costamilam
I’m not able to concatenate the $i variable with $jsonParse.
– Petruceli.L
@Petruceli. L, is your JSON decoding ? Because the way you went is wrong. The right thing would be:
{
 "todos": [{
 "nome1": "andre",
 "cor1": "preta"
 },
 {
 "nome2": "felipe",
 "cor2": "azul"
 },
 {
 "nome3": "laura",
 "cor3": "rosa"
 }
 ]
}
– rbz
if I put jsonParse->right name1 , but put jsonParse->name. $i not right, records only $i values in the bank
– Petruceli.L
RBZ sorry for the way I wrote, but the json is working perfectly. it’s really the way you wrote it. thanks
– Petruceli.L
@Petruceli. L your json is still wrong. Use a validator to check. Ex.: https://jsonlint.com/
– rbz