简体   繁体   中英

Saving Data from Dynamic HTML Table to MySql Database

I'm using this as a reference for my website. I want to save the table's generated data to mysql. anyone have an idea on how to save this? I will not show my code anymore because its all mess up, because i'm trying to save my own table's data. I just need to know how to save this table's data and ill find a work around. Thanks

 <HTML> <HEAD> <TITLE> Add/Remove dynamic rows in HTML table </TITLE> <SCRIPT language="javascript"> function addRow(tableID) { var table = document.getElementById(tableID); var rowCount = table.rows.length; var row = table.insertRow(rowCount); var cell1 = row.insertCell(0); var element1 = document.createElement("input"); element1.type = "checkbox"; element1.name="chkbox[]"; cell1.appendChild(element1); var cell2 = row.insertCell(1); cell2.innerHTML = rowCount; var cell3 = row.insertCell(2); cell3.innerHTML = rowCount; var cell4 = row.insertCell(3); cell4.innerHTML = rowCount; var cell5 = row.insertCell(4); cell5.innerHTML = rowCount; var cell6 = row.insertCell(5); cell6.innerHTML = rowCount; } function deleteRow(tableID) { try { var table = document.getElementById(tableID); var rowCount = table.rows.length; for(var i=1; i<rowCount; i++) { var row = table.rows[i]; var chkbox = row.cells[0].childNodes[0]; if(null != chkbox && true == chkbox.checked) { table.deleteRow(i); rowCount--; i--; } } }catch(e) { alert(e); } } </SCRIPT> </HEAD> <BODY> <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" /> <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" /> <TABLE id="dataTable" border="1"> <tr> <th><INPUT type="checkbox" name="chk[]"/></th> <th>Make</th> <th>Model</th> <th>Description</th> <th>Start Year</th> <th>End Year</th> </tr> </TABLE> </BODY> </HTML>

Following on from your earlier question and this new updated question I put together a demo which I hope will prove useful. Certain assumptions were made ( that you will need to input data into some fields and not just record table row number )

If you save this as a PHP script and run in the browser you can inspect the console to see the results of the Fetch request. It is that Fetch request that you can use to save the data to db.

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        $sql='insert into `table` (`make`,`model`,`description`,`start-year`,`end-year`) values (?,?,?,?,?)';
        $payload=$_POST;
        $payload['sql']=$sql;
        exit( json_encode( $payload ) );
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Add/delete table rows - save to db</title>
        <script>

            document.addEventListener('DOMContentLoaded',(e)=>{

                const tbl=document.getElementById('dataTable');
                const fields=['make','model','description','start-year','end-year'];

                Array.from( document.querySelectorAll('input[type="button"]') ).forEach( bttn=>{
                    bttn.addEventListener('click',function(e){
                        switch( this.name ){
                            case 'add':
                                let tr=tbl.querySelector('tbody').insertRow();
                                let input=document.createElement('input');
                                    input.type='checkbox';
                                    input.name='chk[]';
                                    input.value=1;

                                tr.insertCell().appendChild( input );

                                fields.forEach( ( field, index )=>{
                                    input=document.createElement('input');
                                    input.type='text';
                                    input.name=field;
                                    input.value=index+','+tbl.rows.length;
                                    tr.insertCell().appendChild( input );
                                });
                            break;

                            case 'del':
                                Array.from( tbl.querySelectorAll('input[type="checkbox"]:checked') ).forEach( chk=>{
                                    tbl.querySelector('tbody').removeChild( chk.parentNode.parentNode )
                                });
                            break;

                            case 'save':
                                Array.from( tbl.querySelectorAll('input[type="checkbox"]:checked') ).forEach( chk=>{
                                    /* find all form elements for the row and send XHR request to server to save data */
                                    let data=new FormData();
                                    Array.from( chk.parentNode.parentNode.querySelectorAll('input') ).forEach( input=>{
                                        if( fields.includes( input.name ) )data.append( input.name, input.value );
                                    })

                                    /* using FETCH, send form data to server */
                                    fetch( location.href,{ method:'post', mode:'no-cors', credentials:'include', body:data } ).then( json=>{
                                        console.info( json )
                                    }).catch( err=>{
                                        alert( err )
                                    });
                                });
                            break;
                        }
                    });
                });
            });
        </script>
        <style>
            table{width:80%;border:1px solid black;border-collapse: separate;background:rgba(0,50,150,0.25);color:white;}
            td{border:1px dotted rgba(0,0,0,0.5);margin:2px;padding:0.5rem;background:white;color:black}
        </style>
    </head>
    <body>
        <form method='post'>
            <input type='button' name='add' value='Add row' />
            <input type='button' name='del' value='Delete row' />
            <input type='button' name='save' value='Save to db' />
        </form>

        <table id='dataTable'>
            <thead>
                <tr>
                    <th>&nbsp;</th>
                    <th>Make</th>
                    <th>Model</th>
                    <th>Description</th>
                    <th>Start Year</th>
                    <th>End Year</th>
                </tr>
            </thead>
            <tbody><!-- dynamically generated content --></tbody>
        </table>
    </body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM