thaidomizil Posted June 14, 2011 Share Posted June 14, 2011 Hello, i'm trying to find a way to show a number of text input fields based on a database value, in my mysql table i have a row value called passengers, this is populated with a number that is chosen by a customer, e.g he fills out a booking form for a flight and wants to book the flight for 3 passengers. Now there is a public page generated for each booking that is accessible via customerpage.php?id=x which pulls the data from the mysql db, now on that page i need 2 text input fields generated for each passenger, full name and date of birth, so if the value is 3 (3 passengers) i will need a total of 6 text input fields and so on. What would be the best possible way to achieve this ? Thanks. Quote Link to comment https://forums.phpfreaks.com/topic/239316-show-x-amount-of-text-fields-based-on-db-value/ Share on other sites More sharing options...
Fadion Posted June 14, 2011 Share Posted June 14, 2011 The approach is quite simple. You can treat values from inputs as array elements and manipulating them is pretty easy. Take a look at the following code: <form method="post" action=""> <?php //Input Generation $nr_passengers = 3; for ($i = 0; $i < $nr_passengers; $i++) { ?> <input type="text" name="full_name[]" /><br /> <input type="text" name="date_birth[]" /><br /><br /> <?php } ?> <button type="submit" name="submit">Submit</button> </form> <?php //Form Validation if (isset($_POST['submit'])) { $names = $_POST['full_name']; $dates = $_POST['date_birth']; if (count($names) == count($dates)) { $passengers = array_combine($names, $dates); foreach ($passengers as $key=>$value) { echo $key . '->' . $value . '<br />'; } } } ?> I made 2 inputs that were added to the POST superglobal as arrays (the square braces in the name attribute allow that). In the form validation code, I got those arrays from POST and combined them with array_combine where the passenger name is the key and the date of birth the value. You can further print that combine array ($passengers), manipulate it or whatever you need to do. Quote Link to comment https://forums.phpfreaks.com/topic/239316-show-x-amount-of-text-fields-based-on-db-value/#findComment-1229460 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.