Im trying to figure out the best way of going about this.. I need to be able to append the table row with the input fields using JS so that multiple items can be entered with the same form but I need to somehow make each input have a unique name to target with PHP. From there I need to run a insert statement on each to insert into a mySQL db.. Im kind of stumped here
======================================================================
<form action="" method="post" id="myForm">
<table class="addTable">
<tr>
<th>Title</th>
<th>Type</th>
<th>Quantity</th>
<th>Customer Price</th>
</tr>
<tr>
<td>
<input type="text" name="name" placeholder="Title" maxlength="60" value="<?php echo $_POST['name']; ?>">
</td>
<td>
<input type="text" name="type" placeholder="Type" maxlength="20" value="<?php echo $_POST['type']; ?>">
</td>
<td>
<input type="number" name="qty" placeholder="QTY" max="100" value="<?php echo $_POST['qty']; ?>">
</td>
<td>
<input type="text" name="price" placeholder="Price" value="<?php echo $_POST['price']; ?>">
</td>
</tr>
</table>
</form>
You can use an array as name, for example:
<form action="" method="post" id="myForm">
<table class="addTable">
<tr>
<th>Title</th>
<th>Type</th>
<th>Quantity</th>
<th>Customer Price</th>
</tr>
<tr>
<td>
<input type="text" name="name[]" placeholder="Title" maxlength="60" value="<?php echo $_POST['name']; ?>">
</td>
<td>
<input type="text" name="type[]" placeholder="Type" maxlength="20" value="<?php echo $_POST['type']; ?>">
</td>
<td>
<input type="number" name="qty[]" placeholder="QTY" max="100" value="<?php echo $_POST['qty']; ?>">
</td>
<td>
<input type="text" name="price[]" placeholder="Price" value="<?php echo $_POST['price']; ?>">
</td>
</tr>
</table>
</form>
Then you can use something like:
<?php
for($i = 0; $i < count($_POST['name']; $i++) {
$name = $_POST['name'][$i];
$type = $_POST['type'][$i];
$qty = $_POST['qty'][$i];
$price = $_POST['price'][$i];
// make your query here
}
Also a small advice: in your html code don't directly echo $_POST values, first check if they exist, e. g. <?= isset($_POST['price'])?$_POST['price']:""?>
The <?=
is a shortcut for <?php echo
The isset($_POST['price'])?$_POST['price']:""
part is a shortcut for if-else
statement. (It's called ternary operator)
It means the same as this:
if(isset($_POST['price'])) {
echo $_POST['price'];
} else {
echo "";
}
And the isset()
itself checks whether the variable (or array key in this case) exists.
EDIT: Updated info about appending
If you can use jQuery, it's simple. If you don't use it, start using it :)
<script>
$(document).ready(function() {
$('.some-class-of-your-button').click(function() {
$('.addTable').append($('.addTable tr:nth-child(2)').clone());
$('.addTable tr:last-child input').val("");
});
});
</script>
Replace some-class-of-your-button
with a class that your button has. The button must be outside of the table for this to work.