Morning!
I'm trying to make a login page where our employees can add products to our invoices. I've created a test page for you so you can follow easily and maybe see the idea of this code. On the page our employees can add products to only one invoice right now (because it's a test page) which is invoice_nr 2014002. I want to be able to add multiple products in one form.. I use javascript to add more input fields, but every time I run the query, then it's only inserting the last row.
This is my JavaScript code:
<script type="text/javascript">
function myFunction()
{
var table = document.getElementById("products");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<td>Description <input type="text" name="description" value=""></td>';
cell2.innerHTML = '<td>Qty <input type="text" name="qty" value=""></td>';
cell3.innerHTML = '<td>Price <input type="text" name="price" value=""></td>';
cell4.innerHTML = '<td><input type="button" onclick="removeRow(this)" value="Remove"></td>';
}
removeRow = function(el) {
$(el).parents("tr").remove()
}
</script>
This is the HTML with the form:
<h1>Add more products to invoice</h1>
<form action="" method="post">
<table id="products">
<tr>
<td>Description <input type="text" name="description" value=""></td>
<td>Qty <input type="text" name="qty" value=""></td>
<td>Price <input type="text" name="price" value=""></td>
</tr>
</table>
<br />
<input type="button" onclick="myFunction()" name="addproduct" value="+ Add product"><br /><br />
<input type="submit" name="addproduct" value="Submit new products">
</form>
And last, this is the PHP code..:
require_once("conn.php");
if(isset($_POST['addproduct'])){
$description = addslashes($_POST['description']);
$qty = (int)$_POST['qty'];
$price = addslashes($_POST['price']);
$db->query("INSERT INTO products SET
invoice_nr = 2014002,
description = '".$description."',
qty = '".$qty."',
price = '".$price."'
");
}
And of course, I am aware of the injection on the site, but this is just a basic test page that I've created, because I didn't want to post too much code for you to read otherwise.
I hope it's easy to understand - have a nice day peeps :)