Insert into the database according to the data found

Asked

Viewed 49 times

0

I have a certain problem in "logic", where I must enter the records of two arrays in a table from BD. There I have the following situation:

In the first if I check if the tabela_p does not contain data. If it does not contain, it adds null in tabela_p and inserts according to how much data has the tabela_s;

if(count($tabela_p) == 0){
    $tabela_p = null;
    for( $i = 0; $i < count( $tabela_s); $i ++ ) {

        $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri)
                  values ('$arr_w_param[17]','$tabela_p[$i]','$tabela_s[$i]');"; 

        $w_queryresultado = f_class_conecta_bd($w_querybusca);          
    }
}
else
{
    for( $i = 0; $i < count($tabela_p); $i ++ ) {
        $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri)
                  values ('$arr_w_param[17]','$tabela_p[$i]','$tabela_s[$i]');";                       
        $w_queryresultado = f_class_conecta_bd($w_querybusca);          
    }       
}

Just in the else I enter as per tabela_p; The problem is:

  • If you have a value in tabela_p he falls in the else and will run for only once. But you have the possibility to contain 2 or more data in the tabela_s then he won’t insert them.

As I should do to fix this logic?

  • Do you realize there are some errors in the code? For example, in the first if, where the variable $table_p is set to null, just below you do a for, using $i for the index of the variable $table_p, this will generate an error. for’s for foreach’s

2 answers

1

You use the p as a parameter of for. Use the s, since you want the s set the loop.

Change

for( $i = 0; $i < count($tabela_p); $i ++ ) 

for

for( $i = 0; $i < count($tabela_s); $i ++ )

0

You can do 2 something like:

If you are always sure that there will be value in the variable $table, then just 1 foreach.

foreach ($tabela_s as $key_s => $value_s){
        foreach ($tabela_p as $key_s=> $value_p){
            $w_querybusca="insert into sai_cad_patr_seri (fk_seq_cara_peri,tx_num_patr,tx_num_seri) values ('$arr_w_param[17]',$value_p,'$value_s;"; 
            $w_queryresultado = f_class_conecta_bd($w_querybusca);          
        }
    }

Browser other questions tagged

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