Help with the programming logic

0

I have a div that is made up of some text fields, and a button that calls a js function that duplicates this div if the user clicks ...

Example:

Code:

<divid="duplicar">

<!--.....aqui vai o html dos campos(nao coloquei pq está muito grande)-->     

</div>

<div id="aqui"></div>

<!--botao que chama a função para duplicar a div-->
<div style="width:910px; float:left; margin-right:30px; margin-top:20px;">
    <input type="button" value="+" onclick="mais()"; class="btn btn-outlined btn-success"/>         
</div>

<script>
function mais() {
    var destino = document.getElementById("aqui");
    var novadiv = document.createElement("div");
    var conteudo = document.getElementById("duplicar");
    novadiv.innerHTML = conteudo.innerHTML;
    destino.appendChild(novadiv);
}
</script>

OK, now what I need:

When I submit a form in my form, field values are passed via POST in the form of an array:

item []
qtd []
valueunit []

So if the user duplicates the 3x div for example, the array contains the 3 values entered ...

Now how do I save this array in the database?

-I thought of putting everything together into a string, separating by; (semicolon) ... and save in a column of the bank, this I was able to do using:

//conta o tamanho do array passado via POST
$tam = sizeof($peca);

$grupopeca;

for($c=0; $c < $tam; $c++){
    $grupopeca .= $peca[$c].';'. $qtd[$c].';'.$valorunitario[$c].';';
    #echo $grupopeca;               
}

Now, how do I separate this data when I give a select in the database?

(example if the array is size = 3)
The string will look like this:

  

Washer; 10; 5; Nut; 10; 6; Screw; 10; 7

I need to sort the following into 3 variables:

$ item
$ qtd
$ valorunit

Item: Item #: 5

Item: 6

Item: Qtd:

Item: 7

If there are any other better logic to do this, I accept suggestions.

    
asked by anonymous 23.09.2015 / 11:08

4 answers

2

Charles.

Is there a real reason for you to save everything in a column in the database separating everything with a semicolon? This is a bad practice mainly thinking about the normalization of the bank and the maintenance of its long-term application.

The ideal thing was for you to reshape your database relational entities, thus leaving (for example):

Order Items Table

+----+----------+-------+------------+-----------+
| ID |   Item   |  Qtd  | Valor Unit | Id Pedido |
+----+----------+-------+------------+-----------+
| 1  |  Arruela |  5    |    1.3     |     1     |
+----+----------+-------+------------+-----------+
| 2  |  Porca   |  3    |    0.3     |     1     |
+----+----------+-------+------------+-----------+

Order table

+----+------------------+-----------------+
| ID |        Data      |  Número Pedido  |
+----+------------------+-----------------+
| 1  | 23/09/2015 08:00 |      0001245    |
+----+------------------+-----------------+

And that would make it much easier for you to maintain your application, query, and aggregate your data.

To split the string directly into SQL as you want it will depend a lot on the database you use, many will not support it. So you would have to do this directly in PHP.

MAS If you just wanted to take this string and generate the objects, you could do so. Again I do not recommend this logic the best would be as I said create 2 related tables.

$itensConcatenados  = //aqui seu select que traz a coluna concatenada com ; do seu BD

$itensSeparados = explode(";", $itensConcatenados);

$itens = array();

$indexArray = 0;

while ($indexArray < count($itensSeparados)) { 

    //aqui itera pegando e criando um objeto item a cada 3 posiçõpes do array
    //para isso as informações devem estar sempre na mesma ordem
    $item = new item();
    $item->item = $itensSeparados[$indexArray]->item;
    $item->qtd = $itensSeparados[$indexArray++]->qtd;
    $item->valorunit = $itensSeparados[$indexArray++]->valorunit;

    $itens[] = $item;
}

var_dump($itens);


class item
{
    public $item;
    public $qtd;
    public $valorunit;
}
    
23.09.2015 / 13:43
2

There are several ways you can do this.

BANK (Ideal)

Create separate columns in the database

CREATE TABLE peca{
    id integer NOT NULL DEFAULT nextval('peca_id_seq'::regclass),
    item VARCHAR(255),
    quantidade NUMERIC(12,2),
    valor numeric(12,2)
    CONSTRAINT pk_peca_id PRIMARY KEY (id)
}

In the query via bank, search for specific registry data. So still enabling the research.

JSON

You can convert your array to a JSON save in the bank and after the rollback would already bring in array format again.

$arrayDados = array();
foreach($peca as $k => $value){
    $arrayDados[$k]['pesa'] = $value;
    $arrayDados[$k]['quantidade'] = $qtd[$k];
    $arrayDados[$k]['pesa'] = $valorunitario[$k];
}

In bank save with json_encode($arrayDados) . At the time of retrieving the data you simply retrieve the string generated and deconvert through json_decode($str, true) , thus returning to working with arrayDados .

REGEX

If you do not want to use any of the two techniques above, just grab what you already have and un-hide.

You could use REGEX.

preg_match_all('~([^;]+;[^;]+;[^;]+)~', $str, $match);

$arrayDados = array();
foreach($match[1] as $k => $dados){

    $dados = explode(';', $dados);

    $arrayDados[$k]['pesa'] = $dados[0];
    $arrayDados[$k]['quantidade'] = $dados[1];
    $arrayDados[$k]['pesa'] = $dados[2];
}
    
23.09.2015 / 13:54
1

Within your for place the insert in the table

$tam = sizeof($peca); 
$grupopeca = "";
for ($c=0;$c<$tam;$c++){
    $insert = "INSERT INTO tabela (item, qtde, valor)
                           values ('$peca[$c]',$qtd[$c],$valorunitario[$c])";
    // aqui codigo (PDO/mysql_query)
}

In this way, all records captured from the form will be inserted in the database. It is an example, you should adapt it to your need.

    
23.09.2015 / 13:43
1

The best way is to create a table to add the parts of each order, and get them with a JOIN when calling the order. However, to stay within the scope of your problem, keeping everything in one column, there are two easy ways in PHP:

First, put the pieces in an associative array:

$tam = sizeof($peca);

$grupopeca = [];

for($c = 0; $c < $tam; $c++) {
    $grupopeca[] = [
        'peca' => $peca[$c],
        'qtd' => $qtd[$c],
        'valor' => $valorunitario[$c]
    ];
}

To turn this array into a string, you can serialize it:

$resultado = serialize($grupopeca);

Or turn it into a JSON string (a JSON object actually serialized in string):

$resultado = json_encode($grupopeca);

To revert to getting the bank string:

// Reverter o objeto serializado:
$pecas = unserialize($resultado);

// Reverter o JSON:
$pecas = json_decode($resultado, true);

If you follow this logic of keeping everything in a string column, I recommend the JSON path, which is universally recognized by almost all programming languages, frameworks and databases, and can be interpreted directly by Javascript ( JSON = Javascript Object Notation ).

    
23.09.2015 / 13:48