1

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?

TheOrdinaryGeek
  • 2,273
  • 5
  • 21
  • 47
  • 1
    You should remove the id: `id="mac[]"` because the id has to be unique and any functionality relying on the id automatically is broken. – Adder Aug 17 '18 at 08:59
  • 1
    Use bulk insertion, its a good practice to have one request rather N requests to DB. You can use your loop to build a bulk insert query. [Bulk Insert](https://stackoverflow.com/questions/5526917/how-to-do-a-batch-insert-in-mysql) – Ntwobike Aug 17 '18 at 09:07
  • What if a device has multiple MACs? – Nick Aug 17 '18 at 09:07
  • Check my answer below you can get a idea from that. @TheOrdinaryGeek – Ntwobike Aug 17 '18 at 09:40

2 Answers2

1

Regarding Bulk Insertion: You need to build the sql statement like INSERT INTO table(make, model, mac) VALUES("Apple", "Macbook", 123456),("Apple", "Macbook", 245678),("Apple", "Macbook", 345678); You can get the idea to build the statement from the below code block. NOTE: Also make sure to sanitize the $make, $model, $mac variables Might help

$make = $_POST['make'];
$model = $_POST['model'];
$mac = $_POST['mac'];


$length = count($mac);
$values = [];
for ($i = 0; $i < $length; $i++) {
    $values[] = '("' . $make . '","' . $model . '",' . $mac[$i] .')';
}

$query = "INSERT INTO table(make, model, mac) VALUES". implode(",", $values);
Ntwobike
  • 2,406
  • 1
  • 21
  • 27
  • Please read up on [SQL Injection](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). This code is vulnerable. – Adder Aug 17 '18 at 10:23
0

I have a solution for you. Please use Ajax and FormData.

First, change type submit to button and put id to this button.

Second

$(id).on('click', function() {
  var fd = new FromData();

  var count_mac = $('input[name="mac[]"]').length;
  fd.append('count_mac', count_mac);

  $('input[name="mac[]"]').each(function(index){
     var data = $(this).val();

     //Pass to PHP file with $_POST['mac0'],$_POST['mac1'],...
     fd.append('mac'+ index, data);
  });

  //Ajax code here
  jQuery.ajax({
     url: 'example_file.php',
     type: 'post',
     data: fd,
     contentType: false,
     processData: false,
     success: function( results ) {
       location.reload();
     }
  });
});
Nghia Phan
  • 191
  • 2
  • 10