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
 

Alessandro Branca

Nuovo Utente
13 Ago 2014
5
0
0
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.
 

criric

Super Moderatore
Membro dello Staff
SUPER MOD
MOD
21 Ago 2010
5.607
54
48
TN
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
Autore Titolo Forum Risposte Data
S passare un valore da un form a un file .php con metodo post PHP 4
K Form che manda dati doppi PHP 1
K Problema form update PHP 2
Elisacau [Contact form 7] Inserire Numero auto incrementante WordPress 1
K form Inserimento record mysql PHP 2
I Form con selettore HTML e CSS 0
K [php]form invio dati PHP 0
G form invio multiplo con checkbox PHP 12
nivaria.achinet Intercettare form solo dopo invio Javascript 1
D Form contatti non funzionante HTML e CSS 0
A Stampare dati da form PHP 15
M Unire 2 funzioni per l'invio di un form e con l'apertura di un div Javascript 0
I Form HTML e CSS 17
otto9due $_FILE non passa i dati dal form PHP 1
M Form: come tornare ai campi già compilati dopo invio PHP 1
G Invio form con PHP PHP 3
felino Form action costum e parametri in queryString WordPress 1
M Come recuperare molteplici input form PHP 1
M Collegamento tra form html e script php PHP 4
L form immagini per il database PHP 0
A form PHP prenotazione tramite query PHP 2
A Form php prenotazione di un azienda sanitaria locale presso studio medico PHP 1
L inserimento form dati multipli ? PHP 0
L Problemi form Pagina php HTML e CSS 3
Cosina Creare bottone delete in form upload PHP 5
Cosina Creare bottone delete in form upload PHP 1
D Devo far funzionare un form di contatti PHP 4
B form gestione input PHP 2
V PHP form intersecate PHP 0
8 Javascript - PDF Form Javascript 0
J Form inserimento dati in database Ajax 1
E Gestione profilo utente tramite Form PHP 3
R [C#] Form principale si blocca mentre un altro Thread lavora .NET Framework 0
M Problema con controllo form in real time jQuery 6
D Form validazione Javascript 2
R form recovery pass PHP 0
V Symfony e i form PHP 3
M form con checkbox PHP 8
S come aggiustare un form di contatto? HTML e CSS 3
F query e form con select multipla PHP 17
MarcoGrazia Verifica di una stringa o di un nome proveniente da form Snippet PHP 0
A Inserimento dati nel database tramite form + altre operazioni PHP 18
websilvia Contact form using Bootstrap 3.3.4 PHP 8
Alex_70 Button non funziona nella form PHP 2
C Form email php su pagina index.html? PHP 21
W Rinominare Documenti Con Form Asp Classic ASP 9
S Invio email da form PHP 8
L form multipla php sql,errore in inserimento MySQL 0
L inviare i dati di un form ad un database PHP 6
L Collegare un form html ad un database access Javascript 2

Discussioni simili