Save duplicate arrays to an Insert

Asked

Viewed 38 times

1

Tenhos arrays duplicados

produto[] valor[] qtd[] total[]
produto[] valor[] qtd[] total[]

I need to save these arrays in an Insert, like this:

INSERT 'tabela' (produto, valor, qtd, total) VALUES (produto[],valor[],qtd[],total[]) ;

INSERT 'tabela' (produto, valor, qtd, total) VALUES (produto[],valor[],qtd[],total[]) ;

//OBS: I know this doesn’t work in VALUES but that’s what I need...

I HAVE DONE SO:

    foreach ( $produto as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $valor as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $qtd as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $total as $key => $v) {
    $array[$key][] = $v;
}

    foreach ( $modalidade as $key => $v) {
    $array[$key][] = $v;
}

    foreach( $array as $value){ 

echo "INSERT INTO `table` ( `produto`, `valor`,`qtd`,`total`,`modalidade`) VALUES (".$value[0].",".$value[1].",".$value[2].",".$value[3].",".$value[4].")

}

OBS: It’s working, the fact is that not always in value[0] is the product, and value[1] is the value and so on....

1 answer

2


You can do something like this:

$i=0;
$sql= "INSERT 'tabela' (produto, valor, qtd, total) VALUES ";
while(!empty(produto[$i]){
 $sql=$sql."($produto[$i],$valor[$i],$qtd[$i],$total[$i]),";
$i++;
 }
 $sqlFinal = substr($sql, 0, strlen($sql)-1);

Or another way would be this:

$i=0;
$sql= "INSERT 'tabela' (produto, valor, qtd, total) VALUES ";
foreach($produto as $p){
$sql=$sql."($p,$valor[$i],$qtd[$i],$total[$i]),";
$i++;
}
 $sqlFinal = substr($sql, 0, strlen($sql)-1);

Then you will have sql mounted on the $sql variable

  • Hello friend, I am working with more data not only those that are in the sample code of the question, so checking if the product is filled would not help because I am receiving more data by $_post

  • I don’t think I understand what you mean...

  • I edited there, see if that’s it...

  • I edited the question, showing how I’m doing it. I couldn’t do it the way you told me....

  • I don’t understand what you did there... did you try the way I put it there? because if your arrays key are numbers, each foreach will override the value of foreach anthers, it can give a var_dump($array);to check the qe value inside the array

  • I made a test with its second option and the result was like this: >" INSERT 'table' (product, value, Qtd, total) VALUES ,(t-shirt,99.00,1,99.00),(chalk,199.00,1,199.00) "....

  • I edited there, I changed the comma, so at the end there will always be a comma. Then just remove with the line I added, the last comma. I guess that’s it

  • Perfect friend! Thank you very much...

Show 3 more comments

Browser other questions tagged

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