Register in the bank a separate array

1

I have a API in PHP and an app

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

I would like to know how to register each number and name of that separated in insert line by line?

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

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++;
} 
    
asked by anonymous 17.04.2018 / 20:51

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 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:

  

"The only exception I make is when there are a lot of values, so I do 2 loops, an external one, and an inner one that adds up to N values (50's and 50's). large packets that extrapolate the maximum packet size of the connection. " @Bacco tip.

The hardest part was to understand the question the way it was published before the issues! - Nome: valor data gave the impression that they were column names which were not in the insert

    
18.04.2018 / 02:53
1

I think you can give an explode in the comma and transform into an array, then you put it in a loop and take the values by 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++;
    }

?>
    
17.04.2018 / 20:58