How to insert multiple table rows into database us

2019-09-20 22:49发布

问题:

I have a script that generates for me a table and every time I press a button it generates a row.

When the user press submit I want to insert into the database all rows at once. I tried there something but don't work. I have there the query to insert just one row, but I can't figure out how to insert multiple rows.

Here is my code:

<?php


echo'<!DOCTYPE html>
<html>
    <head>
        <!-- <link rel="icon" type="image/png" href="images/logo4.png"/> -->

        <link rel="stylesheet" type="text/css" href="css/home.css">

        <meta charset="utf-8">

        <meta content="noindex, nofollow" name="robots">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">

        <meta name="viewport" content="width=device-width, initial-scale=1">

        <!--<link rel="stylesheet" href="styles.css"> -->
    </head>

<body>
    <nav>
            <ul class="fancyNav">
                <li><a href="#Instructions">Instructions</a></li>
                <li><a href="#TeachersPage">Teachers Page</a></li>
                <li><a href="#AddNewTable" onClick="genTab()">Add New Table</a></li>
                <li><a href="#StudentsPage">Students Page</a></li>
                <li><a href="#DataBase">Data Base</a></li>
            </ul>
     </nav>

    <div id="content"></div>

   <script>
        var table = \'\'; //table from genTab
        var rows = 1; //for genTab
        var cols = 3; //for genTab
        var rowCounter = 3; //starts from index 3 when add row on table 
        var nr = 2; // write the id at the number
        var tableId = 1; 
        var indexTab=0;


        function genTab() {
            indexTab++;
            table += \'<tr> <th class="window_cells" colspan="3"><form name="form[]" id="formId\'+indexTab+\'" class="window_form" action="home.php" method="post"><span>Coordinator: </span><input type="text" name="prof_name" placeholder="Prof. dr. First Name Last name" required/><input type="email" name="prof_email" placeholder="(email@gmai.com)" required/></form></th> </tr> <tr><td class="window_cells">Nr</td> <td class="window_cells">Theme</td> <td class="window_cells">Details</td> </tr>\';

            for(var r = 0; r < rows; r++)
            {
                table += \'<tr>\';
                for(var c = 0; c < cols; c++)
                {
                    if(c==0)
                        table += \'<td class="window_cells">1</td>\';
                }

                table += \'<td class="window_cells"> <textarea name="theme" rows="4" cols="30" form="formId\'+indexTab+\'"> </textarea> </td>\';
                table += \'<td class="window_cells"> <textarea name="detail" rows="4" cols="30" form="formId\'+indexTab+\'"> </textarea> </td>\';

                table += \'</tr> <tr> <th class="window_cells" colspan="3"> <form id="formTable\'+indexTab+\'"> <input type="button" value="Preview" /><input type="submit" name="submit" value="Submit" form="formId\'+indexTab+\'"/><input id="idRowButton" type="button" value="Add row" onClick="addRow(\'+indexTab+\')"/> </form> </th> </tr>\';
            }       
            document.getElementById("content").innerHTML+=\'<div name="div" class="window_wrap"> <table name="nameWTable" class="window" id="idWindowTable\' +indexTab+\'">\' + table + \'</table> </div>\';


            table = \'\';
        }

        function addRow(intextablou) {

                var windowTab = document.getElementById("idWindowTable"+intextablou);
                var i = 0;

                var roww = windowTab.insertRow(windowTab.rows.length-1);
                var cell1 = roww.insertCell(0);
                var cell2 = roww.insertCell(1);
                var cell3 = roww.insertCell(2);
                //cell1.innerHTML = nr++;
                cell1.innerHTML = (windowTab.rows.length++)-3;
                cell1.className = "window_cells";
                cell2.innerHTML = "<textarea name=\"theme\" rows=\"4\" cols=\"30\"> </textarea>";
                cell2.className = "window_cells";
                cell3.innerHTML = "<textarea name=\"detail\" rows=\"4\" cols=\"30\"> </textarea>";
                cell3.className = "window_cells";
        }


         window.onload = function() {
            genTab();
         }

   </script>
</body>
</html>';

if(isset($_POST['submit'])) {

    $con = mysqli_connect('localhost', 'root', '', 'my_db');

    if(!$con) {
        die("Cannot connect: " . mysql_error());
    }

    $sqlC = "INSERT INTO coordinator (c_name, c_email) VALUES ('$_POST[prof_name]', '$_POST[prof_email]')";

    mysqli_query($con, $sqlC);

    mysqli_close($con);
}

if(isset($_POST['submit'])) {

    $con = mysqli_connect('localhost', 'root', '', 'my_db');

    if(!$con) {
        die("Cannot connect: " . mysql_error());
    }

    $theme = mysqli_real_escape_string($con, $_POST['theme']);

    if(isset($_POST['form[]'])) {

        foreach((array) $_POST['form[]'] as $theme) {
            "INSERT INTO theme (theme) VALUES ('$theme')";
        }

    }

    else {
        echo "nothing";
    }

    $detail = mysqli_real_escape_string($con, $_POST['detail']);

    if(isset($_POST['form[]')) {

        foreach((array) $_POST["form[]"] as $detail) {
            "INSERT INTO theme (t_detail) VALUES ('$detail')";
        }
    }

    else {
        echo "nothing";
    }

    //this works just to insert one row of data.
    //$sqlT = "INSERT INTO theme (theme, t_detail) VALUES ('$_POST[theme]', '$_POST[detail]')";

    //mysqli_query($con, $sqlT);

    mysqli_close($con);
}
?>

回答1:

first you count post value have how many row
then run loop up to the count after that store the result by indexs according your field

 for ($i= 0;$i<=count($_POST['form']);$i++) {   
                "INSERT INTO theme (theme) VALUES ('$_POST['theme'][$i]')";
            }


回答2:

Initially,

You don't need two checks of the POST of 'Submit', you can merge them in to one.

I would suggest you collect the fields as a variable and loop through the variable, which you've almost done but there are a few mistakes. You only need one connection to the database, I would suggest leaving it at the top of your script.

Change

if(isset($_POST['form[]')) {

    foreach((array) $_POST["form[]"] as $detail) {
        "INSERT INTO theme (t_detail) VALUES ('$detail')";
    }
}

The post of 'form[]' won't give you anything, change it to 'form' and assign it to a variable for simplicity, the same format can be replicated with 'themes' as well.

if(isset($_POST['form')) 
{
    $Forms = $_POST['form'];
    foreach($Forms as $detail) {
        $SQL = "INSERT INTO theme (t_detail) VALUES ('$detail')";
        mysqli_query($con, $SQL);

        //You actually need to send this query to the database, at the
        //moment it doesn't do anything
    }
}