Remove data from an array and insert it into the table

1

I include in a array , data entered by the user. But, I only use a array to store data from two fields, where I use "P" (and the data entered) for the first field and "S" (And the data entered) to the second field. So the data gets out of order in array . Example:

array_dados=[P01000213, P154878946, S797465464,P454464654,S48897874, ...]

So, I would like to store the table do banco information in%%. But, "P" and "S" are different fields in array and I only use the letters before the numbers to know which fields they will go to!

My question ... How to remove these letters ( P and S ) and store the data in their proper fields in the table?

Table I need to store the fields:

CREATE TABLE sai_info_dados
(
  seq_info integer NOT NULL DEFAULT nextval('sam_cad_info'::regclass),
  tx_num_prim character varying(12) NOT NULL,
  tx_num_secu character varying(15) NOT NULL
)
    
asked by anonymous 01.10.2014 / 19:15

2 answers

2

Use substr () to remove the first character from $item that way you get the value 'clean' to write to the bank ( $valor ). Then to check which field is to be written you can use $item[0] that takes the first character.

<?php

$arr = array('P01000213', 'P154878946', 'S797465464','P454464654','S48897874');

foreach($arr as $item){
    $valor = substr($item, 1);

    if($item[0] == 'S'){
        echo 'INSERT INTO tabela (s_campo) .... '. $valor  .'<br>';
    }else if($item[0] == 'P'){
        echo 'INSERT INTO tabela (p_campo) ....'. $valor .'<br>';
    }
}
    
01.10.2014 / 19:28
2

To separate the items, you can do something like this:

$tabela_p = array();
$tabela_s = array();

for each ( $array_dados as $item ) {
   if( strtoupper( $item{0} ) == 'P' ) {
       $tabela_p[] = substr( $item, 1 );
   } else {
       $tabela_s[] = substr( $item, 1 );
   }
}

After this loop , you will have two separate arrays with their respective items, without the letters.

Since you did not post the desired insertion criteria, here are some possibilities:

  • You can use foreach in each of $tabela s;

  • You can change the insertion in the arrays by their respective INSERT s;

  • If the result is symmetric, (a P for each S), you can insert the same row in the table with a loop:

    for( $i = 0; $i < count( $tabela_p ); $i ++ ) {
       // 'INSERT INTO ... VALUES( '.$tabela_a[$i].', '.$tabela_s[$i].' )'
    }
    

    (adjust according to the actual case)

01.10.2014 / 19:26