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?):
- How can I make my PHP scale? So it doesn't matter if there is 1 or 1.000.000 input fields without having to list each case in the code (like a loop/foreach)?
- Would it be better to open and close a DB connection for every case or do it like my example above? Isn't there a way to open one connection and push all added information at once? How would I go about this?
Any pointers/helpers much appreciated.