Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Ty Schenk
iOS Development Techdegree Graduate 16,269 PointsDynamic number of Form Inputs
I am trying to build a html form using php so i can have a dynamic number of html form inputs. the number of inputs on the page are pulled from a mysql table but i can't seem to figure out how to do it. example : if mysql results = 5 then it would echo : <input type='text' > 1 <input type='text' > 2 <input type='text' > 3 <input type='text' > 4 <input type='text' >5
If you guys have any idea or suggestions for me to try that would be great. everything helps. :)
Thanks
2 Answers
thomascawthorn
22,986 PointsYo!
You should be able to remove the double quotes around $code
<?php
echo str_repeat($code, $multiples);
Some might find i more readable to use a for loop - it really depends on much dynamic content you have on the input.
<?php
for($i = 0; $i < $multiples; $i++) {
echo '<input type="text" name="some-name">';
}
If all of these inputs are in the same form, you might have trouble doing string repeat - it depends how you've named your inputs. Form inputs with the same name will override each other. Therefore $_POST['some-name'] will always be a single value, no matter how many form fields you submit.
You can do this:
<input type="text" name="some-name[]">
and you'll get back an array of values inside $_POST['some-name'].
You can also do something like this:
<?php
for($i = 0; $i < $multiples; $i++) {
echo '<input type="text" name="some-name-'. $i .'">';
// or
echo '<input type="text" name="some-name['. $i .']">';
}
if you want to be 100% sure you're pulling out the right fields at the right time.
Another way to look at it, hope it helps.
Ty Schenk
iOS Development Techdegree Graduate 16,269 PointsHi Grace, thanks for the reply. I need the html inputs to be based on a number that's in the database. I have a "number of sites" field with a number of 10 so then I would need 10 text inputs for each site name. Please note that the number 10 is never the same and j just there as an example.
Grace Kelly
33,990 PointsGrace Kelly
33,990 PointsHi Ty, just so i understand, is it that you want the number of html form inputs to depend on what is in the database? For example name, age, address, phone number and later on if you add something e.g email address that gets added to the form??