Help with programming logic

Asked

Viewed 93 times

0

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

Example:

inserir a descrição da imagem aqui

Code:

<div id="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>

Okay, now what I need:

When I give a Submit in my form, the values of the fields are passed via POST in array form:

item[]
Qtd[]
valorunit[]

So if the user duplicates the div 3x for example, the array holds the 3 inserted values...


Now how do I save this array to the database?

-I thought of putting everything together in a string, separating by ; (point and comma)...and saving in a column of the bank, this I managed to do using 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 go to give a select in the database?

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

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

I need to separate as follows into 3 variables:

$item
$Qtd
$valorunit

Item: Washer
Qtd: 10
Valor Unit: 5

Item: Nut
Qtd: 10
Valor Unit: 6

Item: Paraduso
Qtd: 10
Valor Unit: 7

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

4 answers

2


Charles.

Is there a real reason why you store everything in a column in the bank separating everything by semicolon? This is a bad practice mainly thinking about the normalization of the bank and the maintenance of its long-term application.

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

Table of order items

+----+----------+-------+------------+-----------+
| 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 it would make your life much easier to maintain your application, make queries and aggregate the data.

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

BUT If you just wanted to take this string and generate the objects, you can do so. Again 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;
}
  • 1

    Actually, using related tables I will have a better control under the values which will help me in the future with the maintenance of the code. Thanks for the help.

2

there are several ways you can accomplish this process.

BANCO (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 database, search for the data from the specific record.
Thus still enabling research.

JSON

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

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

In the bank save with json_encode($arrayDados).
At the time of recovering the data you simply recovers the string generated and disconnected through json_decode($str, true), thus returning to work with the arrayDados.

REGEX

If you don’t want to use either of the above two techniques, just take what you already have and disconnect.

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];
}

1

Inside of your go put 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)
}

This way will be inserted in the BD all captured form records. Is an example, you should adapt it to your need.

  • This way it does not serve me, because I intend to save a STRING inside the GRUPOPECAS field of the bank. The column will be varchar.... and the user can include infinuted parts

  • See I gave you the path. The Insert you can do as you like. A column, several. If you keep the same concatenation, the same example serves. You need to have a key to make the proper moorings. But ideally the table should be normalized as some other colleagues have suggested.

1

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

First, place 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, but serialized in string):

$resultado = json_encode($grupopeca);

To revert when fetching the database string:

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

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

If you are going to 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 mainly be interpreted directly by Javascript (JSON = Javascript Object Notation).

  • The option to use a multidimensional array is a good one, I did some tests this way and it worked. Thanks for giving me that cleared in my mind. However I decided to do with tables in the same banoc, as it will be easier for me to give maintenance in the future.

Browser other questions tagged

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