Reputation: 324
What I am trying to achieve is to have an undefined number of input fields (users are able to add additional input fields with a plus-button on the site). Each input field will have their id/name appended with an increasing number. This is already working fine.
Example:
<input type="text" name="field1" id="field1">
<input type="text" name="field2" id="field2">
<input type="text" name="field3" id="field3">
<button id="addanotherinputfield">+ Add new</button>
So in theory, there could be well more than 200 input fields, the last one then being:
<input type="text" name="field200" id="field200">
I currently push this as $_POST (code simplified):
<?php
$db = new PDO("mysql:host=localhost;dbname=$dbname", $dbtable, $dbpass);
$sdh = $db->prepare('INSERT INTO yeehaw (name,value) VALUES (:name,:value)');
if($_POST['field1'] !='') {
$name = 'field1';
$value = $_POST['field1'];
$sdh->bindParam(':name', $name);
$sdh->bindParam(':value', $value);
$sdh->execute();
}
if($_POST['field2'] !='') {
$name = 'field2';
$value = $_POST['field2'];
$sdh->bindParam(':name', $name);
$sdh->bindParam(':value', $value);
$sdh->execute();
}
if($_POST['field3'] !='') {
$name = 'field3';
$value = $_POST['field3'];
$sdh->bindParam(':name', $name);
$sdh->bindParam(':value', $value);
$sdh->execute();
}
$db = null;
?>
Currently this is working as well.
But for obvious reasons this is not a good way to do it, since it's not scalable (I have to add each case to the code and I like to clean out unnecessary code). I have googled for quit a bit now and can't seem to find the answers to two basic questions (maybe I am looking for the wrong terms/terminology?):
Any pointers/helpers much appreciated.
Upvotes: 0
Views: 2329
Reputation: 57
To make your code much more scalable and less redundant or repeatable i would suggest using a PDO dynamic and automated data binding such as the one listed on Github, its helpful when binding multiple data I have used it a couple of times. It does all the binding for you, here is a link to it on GitHub https://github.com/JstMagic/dynamicPDO Use it in conjunction to Tiles Answer
<input type="text" name="field[]" />
foreach($_POST['field'] as field){ // handle input }
Upvotes: 0
Reputation: 805
Set the name
attribute of your HTML input to be an array to PHP:
<input type="text" name="field[]" />
this way the fields will post as an array an you can easily loop over every field in PHP.
foreach($_POST['field'] as field){
// handle input
}
Upvotes: 3