Form fattura multiriga e query salvataggio mysql

Alessandro Branca

Nuovo Utente
13 Ago 2014
5
0
0
Ciao a tutti,

sono nuovo del forum e vorrei un consiglio.
Sto realizzando un piccolo form per fatture con aggiunta di righe multiple, quindi ho i miei pulsanti per l'aggiunta di una nuova riga, la rimozione di una riga e il salvataggio del tutto che richiama una query mysql.
Sono alle prime armi con php e mysql e, sicuramente, faccio qualche stupidata.

Ora arrivo al problema. Faccio un esempio per capire meglio.
Faccio una nuova fattura con due righe:
| DESCRIZIONE | QT | PREZZO |
articolo1 1 10
articolo2 2 20

Quando vado a fare il salva viene salvata solo l'ultima riga.
Sicuramente è un problema di php, di come ho impostato la cosa.
Non capisco se devo realizzare un array o altro.
Vi posto il codice html con lo script java e il codice php.

Vorrei far notare che quando aggiungo una riga, i campi input prendono sempre gli stessi nomi. Non vorrei che ciò sia parte del problema.

Codice:
<!DOCTYPE html>
<head>
<style type="text/css">
table,tr,td{border:0px solid black;}
</style>
<script type="text/javascript">
    function addRow(tableID) {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[0].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[0].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "text":
                    newcell.childNodes[0].value = "";
                    break;
                case "checkbox":
                    newcell.childNodes[0].checked = false;
                    break;
                case "select-one":
                    newcell.childNodes[0].selectedIndex = 0;
                    break;
            }
        }
    }
    function deleteRow(tableID) {
        try {
        var table = document.getElementById(tableID);
        var rowCount = table.rows.length;
        for(var i=0; i<rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if(null != chkbox && true == chkbox.checked) {
                if(rowCount <= 1) {
                    alert("Impossibile cancellare tutte le righe");
                    break;
                }
                table.deleteRow(i);
                rowCount--;
                i--;
            }
        }
        }catch(e) {
            alert(e);
        }
    }

</script>
</head>

<body>
    <style type="text/css">
    table,tr,td{border:0px solid black;}
    </style>
      <table id="titlebar" cellspacing="0px">
            <tr>
                <td style="width:20px;">✓</td>
                <td style="width:160px;">DESCRIZIONE</td>
                <td style="width:62px;">QT.</td>
                <td style="width:63px;">PREZZO</td>
                
            </tr>
        </table>
        <form action="index.php" method="POST">
      <table id="dataTable" width="auto" style="margin:-4px 0 0 0;" cellspacing="0px">
        <tr>
          <td style="width:20px;"><INPUT type="checkbox" name="chk" /></td>
          <td><INPUT type="text" name="descrizione" style="width:160px;" autocomplete="on" placeholder="DESCRIZIONE" required/></td>
                <td><INPUT type="text" name="qt" style="width:62px;" autocomplete="on" placeholder="QT." required/></td>
                <td><INPUT type="text" name="prezzo" style="width:63px;" autocomplete="on" placeholder="PREZZO" required/></td>
          
          </td>
               
        </tr>
      </table>
        <INPUT type="button" value="AGGIUNGI RIGA" onclick="addRow('dataTable')" />
      <INPUT type="button" value="CANCELLA RIGA" onclick="deleteRow('dataTable')" />
        <INPUT type="submit" value="INVIA"/>
        </form>

</body>
</html>

PHP:
<?php
   
       $con = mysql_connect('localhost', 'xxx', 'xxx') or die ('Errore, non posso fare il login');
       mysql_select_db('test') or die("errore nel selezionare il db");

     $desc = $_POST['descrizione'];
     $qt = $_POST['qt'];
     $pz = $_POST['prezzo'];

     $sql=mysql_query("INSERT INTO tab (id,descrizione,qt,prezzo) VALUES ('','$desc','$qt','$pz')");
   
   mysql_close();
    
    ?>

Grazie a tutti per l'aiuto
 
update:
ho risolto il problema del javascript che creava nuove righe assegnando ad ogni input lo stesso nome.
ho trovato un'altro javascript che però replica l'array presente nel codice html.

CODICE JAVASCRIPT:
Codice:
function addRow() {
    /* Declare variables */
    var elements, templateRow, rowCount, row, className, newRow, element;
    var i, s, t;
    
    /* Get and count all "tr" elements with class="row".    The last one will
     * be serve as a template. */
    if (!document.getElementsByTagName)
        return false; /* DOM not supported */
    elements = document.getElementsByTagName("tr");
    templateRow = null;
    rowCount = 0;
    for (i = 0; i < elements.length; i++) {
        row = elements.item(i);
        
        /* Get the "class" attribute of the row. */
        className = null;
        if (row.getAttribute)
            className = row.getAttribute('class')
        if (className == null && row.attributes) {    // MSIE 5
            /* getAttribute('class') always returns null on MSIE 5, and
             * row.attributes doesn't work on Firefox 1.0.    Go figure. */
            className = row.attributes['class'];
            if (className && typeof(className) == 'object' && className.value) {
                // MSIE 6
                className = className.value;
            }
        } 
        
        /* This is not one of the rows we're looking for.    Move along. */
        if (className != "riga")
            continue;
        
        /* This *is* a row we're looking for. */
        templateRow = row;
        rowCount++;
    }
    if (templateRow == null)
        return false; /* Couldn't find a template row. */
    
    /* Make a copy of the template row */
    newRow = templateRow.cloneNode(true);

    /* Change the form variables e.g. price[x] -> price[rowCount] */
    elements = newRow.getElementsByTagName("input");
    for (i = 0; i < elements.length; i++) {
        element = elements.item(i);
        s = null;
        s = element.getAttribute("name");
        if (s == null)
            continue;
        t = s.split("[");
        if (t.length < 2)
            continue;
        s = t[0] + "[" + rowCount.toString() + "]";
        element.setAttribute("name", s);
        element.value = "";
    }
    
    /* Add the newly-created row to the table */
    templateRow.parentNode.appendChild(newRow);
    return true;
}

CODICE HTML:
Codice:
<form action="index.php" method="post">
   <table>
<tr><th>nome</th><th>quantita</th><th>prezzo</th></tr>
<tr class="riga">
  <td><input type="text" name="descrizione[0]"/></td>
  <td><input type="text" name="quantita[0]"/></td>
  <td><input type="text" name="prezzo[0]"/></td>
</tr>
</table>
<div><input type="submit" /></div>
<div><a onclick="addRow(); return false;" href="#">Aggiungi riga</a></div>
</form>

Ora il problema sta tutto nella query.
La tabella è cosi composta:
id | descrizione | quantita | prezzo
Quando salvo le righe che ho inserito trovo il valore id corretto (autoincrementale), nella voce descrizione trovo solo la voce Array e nei campi quantita e prezzo trovo 0 (in quanto i campi sono impostati relativamente come interi per quantità e decimale come prezzo).

Vorrei che per ogni riga che creo nel form si creasse una riga nel database con valori corretti per ogni campo.
 
Ciao, non sono riuscito a far funzionare il secondo script che hai postato,ma , secondo me c'è troppo javascript
ti posto un idea che mi è venuta in mente
PHP:
<?php
if (isset($_POST['submit'])) {
    unset($_POST['submit']);
    $i = 0;
    foreach ($_POST['descrizione'] as $value) {
        $query = "INSERT INTO tabella 
                         SET desc = '" . $value . "',
                             qta = '" . $_POST['quantita'][$i] . "',
                             pzzo = '" . $_POST['prezzo'][$i] . "'";
        echo $query . "<br/>";
        $i++;
    }
}
?>
<script type="text/javascript">
    function addRow() {
        var tb = document.getElementById("tab").getElementsByTagName("tbody")[0];
        var tr = tb.getElementsByTagName("tr")[0].cloneNode(true);
        tb.appendChild(tr);
    }
</script>
<form action="" method="post">
    <table id="tab">
        <thead>
            <tr><th>nome</th><th>quantita</th><th>prezzo</th></tr>
        </thead>
        <tbody>
            <tr>
                <td><input type="text" name="descrizione[]"/></td>
                <td><input type="text" name="quantita[]"/></td>
                <td><input type="text" name="prezzo[]"/></td>
            </tr>
        </tbody>

    </table>
    <input type="submit" name="submit" value="Invia"/>
    <a onclick="addRow(); return false;" href="#">Aggiungi riga</a></div>
</form>
Calcola che non l'ho testata, è solo un'idea
 

Discussioni simili