Using PHP I'm building a web form that will allow people to submit details of network devices registered to them, these details are saved in a mysql database. I want to allow users to submit multiple devices on the same form.
The details I need to collect are;
- make
- model
- mac address
A user may need to register 20 identical devices, i.e. the same make and model, the only field that will change is mac address. Rather than ask users to submit 20 separate forms I have a button 'Add Similar Device', using JQuery this creates a new mac address input (array type).
All is working as expected but I'm not sure if i'm doing it 'the right way', so I was hoping for some advice - my code is below;
HTML
<form id="myForm" method="POST" action="">
<input id="make" name="make" type="text">
<input id="model" name="model" type="text">
<input id="mac[]" name="mac[]" type="text">
<!-- example of two dynamically added mac inputs
<input id="mac[]" name="mac[]" type="text">
<input id="mac[]" name="mac[]" type="text">
-->
<input id="submit" name="submit" type="submit">
</form>
<button class="add-similar" id="add-similar" type="button"></button>
JQuery
<script>
$(document).ready(function() {
var maxField = 10;
var addButton = $('.add-similar');
var html = '<input id="mac[]" name="mac[]" type="text">';
var x = 1;
$(addButton).on('click', function(e) {
if (x < maxField) {
x++;
$(wrapper).append(html);
}
});
});
</script>
PHP
if(isset($_REQUEST["submit"])){
$make = $_POST['make'];
$model = $_POST['model'];
$mac = $_POST['mac'];
for ($i = 0; $i < count($mac); $i++) {
// insert data into db
}
}
For every additional mac address input dynamically added, I need to create a new, unique record in the db. If two dynamic mac addresses are added, the db table should look like this;
+----+-------+---------+--------------+
| id | make | model | mac |
+----+-------+---------+--------------+
| 1 | Apple | Macbook | 112233445566 |
+----+-------+---------+--------------+
| 2 | Apple | Macbook | 998877665544 |
+----+-------+---------+--------------+
| 3 | Apple | Macbook | 887766225533 |
+----+-------+---------+--------------+
Am I approaching this the right way?