Save data from an html table in PHP array

Asked

Viewed 1,045 times

2

I have an html generated table and the data of each row needs to be saved to a table in the database. Each row represents an item of a shopping cart. The structure is this:

<table class="table table-sm table-bordered table-striped" id="tblItens">
<thead>
    <tr>
        <th style="width: 10%">ID</th>
        <th style="width: 36%">Descrição</th>
        <th style="width: 12%">Valor</th>
        <th style="width: 10%">Qtde</th>
        <th style="width: 10%">Desc</th>
        <th style="width: 12%">Total</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>Lápis</td>
        <td>2.00</td>
        <td>5</td>
        <td>0.00</td>
        <td>10.00</td>
    </tr>
    //e assim por diante...
</tbody>
</table>

As tr are automatically generated when an event is triggered to collect data from another table that exists on the page. The function is called on that button:

<i class="fas fa-plus" title="Adicionar" onclick="adicionarItem(this)"></i>

Javascript function:

function adicionarItem(e){

    var linha = $(e).closest("tr");

    var nome = linha.find("td:eq(0)").text().trim()
    var precoVenda = linha.find("td:eq(1)").text().trim()
    var id   = linha.find("td:eq(3)").text().trim()
    var precoCusto = linha.find("td:eq(4)").text().trim()

    var table = document.getElementById("tblItens")
    var numOfRows = table.rows.length
    var newRow = table.insertRow(numOfRows)

    newCell = newRow.insertCell(0)
    newCell.innerHTML = ""+ id

    newCell = newRow.insertCell(1)
    newCell.innerHTML = ""+ nome

    newCell = newRow.insertCell(2)
    let inputValor = document.createElement('input')
    inputValor.type = 'text'
    inputValor.id = 'valorProduto'
    inputValor.className = 'form-control form-control-sm'
    inputValor.value = precoVenda
    newCell.appendChild(inputValor)

    newCell = newRow.insertCell(3)
    let inputQtd = document.createElement('input')
    inputQtd.type = 'text'
    inputQtd.id = 'qtdProduto'
    inputQtd.className = 'form-control form-control-sm'
    inputQtd.value = 1
    newCell.appendChild(inputQtd)

    newCell = newRow.insertCell(4)
    let inputDesc = document.createElement('input')
    inputDesc.type = 'text'
    inputDesc.id = 'descProduto'
    inputDesc.className = 'form-control form-control-sm'
    inputDesc.value = 0
    newCell.appendChild(inputDesc)

    newCell = newRow.insertCell(5)
    let inputTotal = document.createElement('input')
    inputTotal.type = 'text'
    inputTotal.id = 'totalProduto'
    inputTotal.className = 'form-control form-control-sm'
    inputTotal.value = precoVenda
    newCell.appendChild(inputTotal)

    newCell = newRow.insertCell(6)
    newCell.className = 'opcoes'
    let inputEdit = document.createElement('i')
    inputEdit.className = 'fas fa-sync-alt'
    inputEdit.title = 'Editar'
    inputEdit.id = 'iEditar'
}

I would like to know how I can use a php function to take the data from each line and place it in an array. I have no idea how to use a loop for that.

  • Would that help you? I know it’s not the same problem, but it’s similar, I believe. https://answall.com/questions/39096/imprimir-dados-array-php?rq=1

  • why do you want to do this?

  • I need to take these values to save in a table in the database after, are the items of a respective purchase.

  • 1

    I asked this question, because you must be doing it in the most complicated way, because if it’s just this page, you can do it on hand even if it will already solve your problem, but if it is several pages, you will have more work to do on the other pages, running one script at a time, what I wanted to know is why you need to get this information from an html page.

  • where does the table data come from? vc will do in hand?

  • Wictor and Lodi, I edited the post, please see if you can understand better now. And it’s only on this page that I really need Wictor.

  • You can create an array at the time you are adding the items, and when sending, send this array via ajax to your php page.

Show 2 more comments

1 answer

1


You can take the data using Jquery and send it via ajax to your php page, the code is explaining through the comments.

var indices = [];

//Pega os indices
$('#tblItens thead tr th').each(function() {
  indices.push($(this).text());
});

var arrayItens = [];

//Pecorre todos os produtos
$('#tblItens tbody tr').each(function( index ) {

  var obj = {};
  
  //Controle o objeto
  $(this).find('td').each(function( index ) {
    obj[indices[index]] = $(this).text();
  });
  
  //Adiciona no arrray de objetos
  arrayItens.push(obj);
  
});

//Mostra dados pegos no console
console.log(arrayItens);

//Envia para o php
$.ajax({
  type: "POST",
  url: "suapagina.php",
  data: arrayItens,
  success: function(respostaDoPhp){
    alert('Deu tudo certo');
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-sm table-bordered table-striped" id="tblItens">
<thead>
    <tr>
        <th style="width: 10%">ID</th>
        <th style="width: 36%">Descrição</th>
        <th style="width: 12%">Valor</th>
        <th style="width: 10%">Qtde</th>
        <th style="width: 10%">Desc</th>
        <th style="width: 12%">Total</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td>1</td>
        <td>Lápis</td>
        <td>2.00</td>
        <td>5</td>
        <td>0.00</td>
        <td>10.00</td>
    </tr>
    <tr>
        <td>1</td>
        <td>Lápis1</td>
        <td>2.00</td>
        <td>5</td>
        <td>0.00</td>
        <td>10.00</td>
    </tr>
    <tr>
        <td>1</td>
        <td>Lápis2</td>
        <td>2.00</td>
        <td>5</td>
        <td>0.00</td>
        <td>10.00</td>
    </tr>
</tbody>
</table>

  • Wictor, the problem is that on the page there is more than one table, how do I identify it by id ?

  • Yes, you can use the table id, I will edit my reply using the table id

  • 1

    Okay, I edited using the table id, I just put "#tblItens", which is the id relative to that table.

  • Thank you very much, it worked correctly. Last question, I saw that you used the "$(this). text();" to get the text inside the <td> and, in my case I have a <input>, what I should do ?

  • to get inputs just put $(this). val(), when you use val you take input value

  • I tried to replace it with val() it does not take the values, leaves it empty. I have to define some condition ?

  • I do the following here, I do a foreach $(this). find('td'). each( taking all td, ie when I do the "$(this)" reference, I am referencing the "td", if your input is within "td", I will have to make $(this). find('input'). val(), i.e., it selects td and then input and then takes the input value

Show 2 more comments

Browser other questions tagged

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