Jump to content

Recommended Posts

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.

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.