Register a separate array in the database

Asked

Viewed 102 times

1

I have a API in PHP and a app done with Ionic 3.

I’m getting from the app a string this way "200,300,40" and the same thing "polimento,pintura,lavagem".

I would like to know how to register each number and name of this separate on insert line by line ?

There are other data besides these numbers like date etc.. but it comes only a simple record without comma type: 23/04/2016 I would have no problem repeating them on the bank line". So I wanted it to stay line by line.Like:

nome_servico     valor_servico    data_servico   id_usuario   .......
polimento        200              23/04/2016
pintura          400              23/04/2016
lavagem          40               23/04/2016

$count= 0;
$max = count($varnome);
while($count <= $max){
$sql = "insert into pedido(nome_servico,valor_servico,id_usuario,total_servico,data_servico,id_empresa,n_pedido)values('".$varnome[$count]."','".$varvalor[$count]."','".$id_usuario[$count]."','".$total_servico[$count]."','".$data_atual[$count]."','".$id_empresa[$count]."','".$comp_ped[$count]."')";
$count++;
} 

2 answers

3

Use the loop to generate the string,

$count= 0;
$max = count($varnome);
while($count < $max){
  $values .="'".$varnome[$count]."', '".$varvalor[$count]."', '".$id_usuario."', '".$total_servico."', '".$data_atual."', '".$id_empresa."', '".$comp_ped."'),(";  
  $count++;
}

and after the loop do the Insert

//retira os 3 caracteres indesejáveis no final
$values= substr($values,0,-3); 

$sql = "INSERT INTO pedido(nome_servico,valor_servico,id_usuario,total_servico,data_servico,id_empresa,n_pedido) VALUES ($values)";

$query = $db->prepare($sql);
$query ->execute();

Nevertheless, I believe the expected result is:

inserir a descrição da imagem aqui

"the only case I make exception is when there are many values. There I make 2 loops. One external, and one internal that joins up to N values. (from 50 to 50, for example) but this to avoid very large queries that exceed the maximum size of the connection data package." tip from @Bacco.

The hardest part was understanding the question the way it was published before the issues! suando.gif - Nome: valor data gave the impression that they were names of columns which did not appear in the declaration insert

1

I think you can blow up the comma and turn it into an array, then you put it in a loop and take the values by the index

<?php
    $nome = $stringNome.explode(",");
    $code = $stringCodigo.explode(",");
    $count = 0; //contador para pegar o index
    $max = count($nome); // numero maximo de registros

    while($count <= $max){
       mysql("sua query aqui VALUES('".$nome[count]."','".$code[count]."')");
       $count++;
    }

?>
  • I didn’t understand your comment

Browser other questions tagged

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