How to insert data to a mysql database from an HTML Table

前端 未结 2 1316
南方客
南方客 2021-01-03 07:13

I have a HTML table with information. Right now I can add rows and delete the rows with a button using javascript. I can a

2条回答
  •  抹茶落季
    2021-01-03 07:28

    Yes.. You have good JavaScript code to adding dynamic content..wow.. Now you want to insert that content to MySQL table..yes you can... Before that small modification to do your code.. First you should understand insert something to database, you have a HTML form element.. and controls..you can add dynamically HTML form element as following

      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 = "";
    
            var cell3 = row.insertCell(2);
            cell3.innerHTML = "";
    
            var cell4 = row.insertCell(3);
            cell4.innerHTML =  "";
            }
    

    keep your delete method same, but change this line only

    var i=1
    

    to

    var i=0
    

    Now Change your HTML code as following , make sure your table body tag has a id named "dataTable", and remove you check box ,put form element to cover your table..bang...

    
    
    
    
    
    Item Price Qty

    // create mysql database and then create table // following is the example

    CREATE TABLE `your_table_name` (
      `id` int(11) NOT NULL auto_increment,
      `item` varchar(200) NOT NULL,
      `price` varchar(200) NOT NULL,
      `qty` varchar(200) NOT NULL,
      PRIMARY KEY  (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
    

    greate ... now this is the interesting part.. I use the php language to insert data to database.. make sure you should create database connection..

     $value) 
            {
                $item = $_POST["item"][$key];
                $price = $_POST["price"][$key];
                $qty = $_POST["qty"][$key];
    
                $sql = mysql_query("insert into your_table_name values ('','$item', '$price', '$qty')");        
            }
    
        }   
    ?>
    

    I think this post is important to all ..

提交回复
热议问题