Log in

View Full Version : Dynamic Form Content, Array, MySQL



Rel82me
01-11-2014, 08:44 PM
For anyone who can provide some assistance I would appreciate it.

Have a portion of a registration system that asks the end user for a URL, then allows the user to add additional URLS's by clicking the "Add Additional URL" button & function. Here's the Form portion:

------------
<td>
<div id="dynamicInput">Uniform Resource Locator 1:<br><input type="text" name="myInputs[]" placeholder="http://www.mydomainname.com">
</div><br/>
<input type="button" value="Add Additional URL's / Domains" onClick="addInput('dynamicInput');">
</td>

-------------

Here's the function portion:

-------------
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Uniform Resource Locator: " + (counter + 1) + " <br><input type='text' name='myInputs[]' placeholder='http://www.mydomainname.com'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}</script>
---------------

How do I get this array into my database table? The database portion works, no problem as all the other user info get's inserted and of course, I already have fields for the 3 additional URL's.

I'm assuming else statement is generating the following variables, dynamically: myInputs[0], myInputs[1], myInputs[2] or ..1..2..3. So not to sure if I should be using:

$myInputs1 = $_POST['table field name'];
$myInputs2 = $_POST['table field name''];

then a sql insert statement, or what??


maybe foreach($_POST as ........)

???

traq
01-12-2014, 12:00 AM
First, how to access the form inputs: easiest way would likely be foreach( $_POST['myInputs'] as $myInput ){ … .

Next, how to get the array into the database: don't. There's no such thing as an array in an SQL database. The best solution is to use another table for the items in the array, with a foreign key to associate them with table (and rows) they belong to. I don't know the specifics of your DB structure or the data you need to store, but here's the general idea:
CREATE TABLE `user`(
`id` SERIAL PRIMARY KEY,
-- (other user fields)
)ENGINE=InnoDB;

CREATE TABLE `userURL`(
`url` VARCHAR (100) NOT NULL,
`user` SERIAL,
PRIMARY KEY (`user`,`url`),
FOREIGN KEY (`user`) REFERENCES `user` (`id`)
)ENGINE=InnoDB;

In this way, your array can be represented as SELECT url FROM userURL WHERE user=:desiredUserID.


If you need more help, please give more information.