I'm trying to ask a user how many guests. Once the user has entered a number then a number of fields should appear where the user can then add guest1, guest2 etc. However every time I try and create a for loop it doesn't seem to be working. This is the current source code for entering the number of guests.
<? echo "<input type='text' name='guestnumber' size='6' value='$guestnumber'>" ?>
What I would like to happen is that the name of the textfields would be guest1, guest2 etc based on the number of guests they have entered. I'm sure it's a pretty simple for loop that needs to be done but I'm not sure how to do it.
Here is a basic example. Submitting the form does not reset the fields.
You can either store all values in separate variables such as $guest1, $guest2, etc, but an array is much easier to use when handling the $_POST data.
Before touching any of the variables we check if the variable is set with isset to prevent errors.
<?php
// Set up the number of guests
if(isset($_POST['guestnumber'])) {
$numGuests = (int)$_POST['guestnumber'];
if ($numGuests < 1) {
$numGuests = 1;
}
}
if (isset($_POST['guests'])) {
// Handle guest data
}
?>
<form method="POST" action="">
<input type="text" name="guestnumber" size="6" value="<?php
// Retain field value between refreshes
if(isset($numGuests)) echo $numGuests; ?>"><br>
<?php
// Echo out required number of fields
if (isset($numGuests)) {
for ($i = 0; $i < $numGuests; $i++) {
// Store field information in a 'guests' array
echo "<input type='text' name='guests[]' value='";
// Retain the guest names between refreshes
if (isset($_POST['guests'])) {
echo $_POST['guests'][$i];
}
echo "'><br>";
}
}
?>
<input type="submit" value="Submit">
</form>
Related
Hoping someone can steer me in the right direction. I have a form with an input field and a button. When the input field is populated and the button clicked the value of the field displays in the variable $capture_numbers.
Id like to be able to add to that value i.e person enters 1, $capture_numbers displays 1, person enters 2, $capture_numbers now displays 1, 2, person enters 3, $capture_numbers now displays 1, 2, 3 and so on. I'm thinking along the lines of storing the previous value and appending to it but cant figure out how it's done. Below is my script.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<fieldset>
<input type="text" name="mynumbers[]">
<button>add another numbers</button>
<input type="submit" value="Submit" title="submit">
</fieldset>
</form>
<?php
if(isset($_POST['mynumbers']) && is_array($_POST["mynumbers"])) {
$capture_numbers = ' ';
foreach($_POST["mynumbers"] as $key => $value) {
$capture_numbers .= $value .", ";
}
echo $capture_numbers;
}
?>
You will need some persistent storage to store previous submissions. Valid options are a database, local storage, cookies, session etc.
In this example, I used session. When the form is submitted, check the session for previous entries and then append the new one to the list. I've added comments in the code.
Edit: You don't need to add the text field as an array. Ie. name="mynumbers[]". That is usually used for when you have multiple inputs with the same name and want to read them as an array.
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<fieldset>
<input type="text" name="number">
<button>add another numbers</button>
<input type="submit" value="Submit" title="submit">
</fieldset>
</form>
<?php
// Start the session
session_start();
// Check if form is submitted
if (!empty($_POST)) {
// Create a variable to store all numbers
$allNumbers = [];
// Does the session contain anything
if (isset($_SESSION['previous'])) {
// Grab it from the session as an array and store it
$allNumbers = explode(',', $_SESSION['previous']);
}
// Append the new number to the list
$allNumbers[] = $_POST['number'];
// Convert it to a comma separated string
$capture_numbers = implode(',', $allNumbers);
// Store the entire list in the session
$_SESSION['previous'] = $capture_numbers;
// Output the result
echo $capture_numbers;
}
Briefly, my script includes form ask how many images to enter ,,the entered value will be in a while loop that will display a form with inputs equally to image value entered . okey , I made the submit button outside the loop ,I want now to add them to database ,,I used again a while loop with the query as I did in the form ,,but it only inserts the last item ..What could the problem be ? This is part of the script :
if (isset($_POST["chooseimagen"])) {
$i=0;
$imgvl = $_POST["imgvl"];
$cid = $_POST["cid"];
while($i<$imgvl){
echo '<form name="finalform" method="post" action="">
id of content :<input type="text" name="idcontent" value="'.$cid.'"/><br><br>
Enter id of image :<input type="text" name="imgid" value=""/><br><br>
Enter name of image : <input type="text" name="imgname" value=""/><br><br>
-----------------------------------------------------------------------<br>
';
$i++;
}
echo "<br><br><input type='hidden' name='imgvl' value='".$imgvl."'/><input type='submit' name='addto' value='insert images'/></form";
}
?>
<?php
if(isset($_POST["addto"])){
$imgvl = $_POST["imgvl"];
$i=0;
while ($i < $imgvl){
$idcontent = $_POST["idcontent"];
$imgid = $_POST["imgid"];
$imgname = $_POST["imgname"];
$queryin = "insert into content_images values ('$imgid','$idcontent','$imgname','ok')";
mysqli_query($con,$queryin);
$i++;
}
}
?>
Still new to development, but I think I know..
A few things, you are creating a new form with every loop, but only closing it once. Also you are missing a >, so technically you are not closing the forms at all.
while($i<$imgvl){
echo '<form name="finalform" method="post" action="">
...
$i++;
}
echo "<br><br><input type='hidden' name='imgvl' value='".$imgvl."'/>
<inputtype='submit' name='addto' value='insert images'/></form";
But I think the reason you are getting this problem is each form you create has the same names for the inputs. That's why you are only getting the last item, because every item you are inserting is just the last input set.
Because you have no action on the form, every form is essentially combined. This means there is no way to distinguish which input name you are reffering to and therefore it takes the last value that was assigned.
Hope this helps
I am trying to write a dynamic form using PHP. I'd like to have a single webpage that contains two forms:
The upper form allows to search for an element in the mysql database, e.g., for a name
The lower form shows the data that is associated with this name in the database
If I press on the "Search" button of the upper form, then the the lower form is shown and the text fields are filled with data from the database that belong to this name. If I change the user name to some other value and press again "Search", then the data that is associated with the new record is shown and so on.
The lower form also has a button "Update" which allows to transfer changes made to the text boxes (in the lower part) to the database.
Now, I have the following problem: In my script I set initially the value of name (from the upper form) to "". When I then press the "Search" button, then the lower part of the form is shown and the corresponding data is shown in the lower part. When I then press the "Update" button, then the text field associated with name is set to the empty string. This is because in my script I set initially name to the "". I'd like that in this case the data entered in the upper form is not changed, i.e., it stays the same.
I guess, I am missing something here. There is probably an easy solution for this and I am doing something fundamentally wrong. It'd be great if you could help me.
That's what I tried... I deleted lots of details, but I guess that can give you an idea what I am trying to do. Notice that the whole code is in the file update.php.
<?php
function search_bus($mysql, $name)
{
// do some stuff here...
}
function update_bus($mysql, $b_id)
{
// do some stuff here...
}
// some global variables
$b_id = 0;
$username = ""; // username of business
// get b_id that corresponds to username
if (isset($_REQUEST['search']))
{
$b_id =0; // business id
if (isset($_POST['user']))
{
$username = $_POST['user'];
$b_id = search_bus($mysql, $username);
}
}
elseif(isset($_REQUEST['update']))
{
update_bus($mysql, $b_id);
}
?>
<h2>Search:</h2>
<form name="search_bus" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="submit" value="Suchen" name="search"/>
</form>
<?php
if($b_id != 0)
{
?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<-- some form follows here -->
<?php
}
?>
I think what you're missing is to create a HTML Hidden field to keep the value of Name variable.
<input type="hidden" name="name" value="<?php print $nameVar ?>" />
Add this input to both forms so you can keep the value no matter what button the user clicks.
Hope this helps.
Adding code to verify the
<h2>Search:</h2>
<form name="search_bus" method="post"
action="<?php echo $_SERVER['PHP_SELF'];?>">
Username: <input type="text" name="user" value="<?= htmlentities($username) ?>"/>
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<input type="submit" value="Suchen" name="search"/>
</form>
<?php if($b_id != 0) { ?>
<h2>Data:</h2>
<form name="business_design" method="post" action="<?php echo $_SERVER['PHP_SELF'];>">
<input type="hidden" name="b_id" value="<?php print $b_id?>" />
<-- some form follows here -->
<?php } ?>
Dont initialize $b_id if it already comes into the http request.
if (!isset($_POST['b_id']))
{
$b_id = 0;
}
else
{
$b_id = $_POST['b_id'];
}
This way you can alway remember the last selected value of b_id.
Hope this can help you.
I am trying to create a "report" that can be filtered using a form on the top of the page. The options to filter the results is the Fiscal Year which is the current FY by default and multiple categories (check boxes) which are all checked by default. The page generates properly with the default data but when the form is submitted the page will "refresh" but there is no POST data generated. I tried creating a copy of the page and setting it as the action URL but it still did not have any POST data and used the defaults. I will include my code below and will try to narrow it down to just the necessary parts to make it easier but can share all of it if need be. Thank you in advance for any help offered.
<body>
<?php
if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}
// Establish Connection and Variables
// Connection
include "./include/class/DBConnection.php";
DBConnection::$dsn;
DBConnection::$user;
DBConnection::$pass;
DBConnection::getDBConnection();
// The Current Fiscal Year
$today = getdate();
$month = $today['month'];
// seperate first and second half of fiscal year
$old = array('January','February','March','April','May','June');
if (in_array($month,$old)) {
$year = $today['year'] + 1;
}
else {
$year = $today['year'];
}
// Create SQL Query Variables - Removed for post
// Set filter criteria
// Retrieve array of possible categories and create SQL WHERE statment
$catAllCxn = DBConnection::$cxn->prepare($SQL_Categories);
$catAllCxn->execute();
$catAllCxn->setFetchMode(PDO::FETCH_ASSOC);
$catAllArray = array();
while($catAllRow = $catAllCxn->fetch()) {
$cat = $catAllRow['Category'];
array_push($catAllArray, $cat);
}
$catAllInQuery = implode(',',array_fill(0,count($catAllArray),'?'));
// Create array for category filter IF form was submitted to itself
if (isset($_POST['submit'])){ // if page is submitted to itself
$catFilterArray = $_POST['Category'];
$catFilterInQuery = implode(',',array_fill(0,count($catFilterArray),'?'));
}
// Switch for ALL or Filtered report
if(!isset($_POST['submit'])) { // if page is not submitted to itself
$FiscalYear = $year;
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catAllArray;
$IncludedCategories = $catAllInQuery;
}
else {
$FiscalYear = $_POST["FiscalYear"];
// $DiscludedDepartmentNumbers = "21117";
$catArray = $catFilterArray;
$IncludedCategories = $catFilterInQuery;
}
?>
<!-- Filter Form -->
<div id="filters" style="border: 1px solid;">
<form name="filter" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
Fiscal Year: <input type="text" name="FiscalYear" value="<?php echo $FiscalYear; ?>" /> <?php if(isset($_POST['submit'])){echo"SET";} else{echo"NOT SET";}?>
<br />
<fieldset>
<legend>Select Categories</legend>
<?php
foreach($catAllArray as $catAllRow) {
if (!isset($_POST['submit'])) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else if(in_array($catAllRow,$catArray)) {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" checked=\"checked\" />".$catAllRow." \n";
}
else {
echo "<input type=\"checkbox\" name=\"Category\" value=\"".$catAllRow."\" />".$catAllRow." \n";
}
}
?>
</fieldset> <br />
<input type="submit" value="submit" />
</form> <!-- End: filter -->
</div> <!-- End: filters -->
From here the original code continues to output results into a table but this works properly and I don't think it is the problem. I can share more if asked.
You need to give the submit button a name, if that's what you're using to check if the form is submitted...
<input type="submit" value="submit" name="submit" />
Or if you dont want to change the submit button, you can check isset on the category input instead
if(isset($_POST['Category'])){echo"SET";} else{echo"NOT SET";}
I think that your check if there is a _POST value is wrong. try this:
if(isset($_POST['FiscalYear']))
And see if that works
you need to name your submit button if you want to check for it
<input type="submit" value="submit" name="submit" />
otherwise php will not place it in the $_POST array
OK that probably sounded a bit confusing but what I have is a table that spits out courses locations and dates depending on what the user chooses. I than want the user to go through the fields and than on the 3rd submit button I have the course information displayed to them. I'm asking how in php i can take the echo from the first query and use that to upload it to the other table. Would I just be using MySQL Links?
If you have multiple pages, you can use $_SESSION variables to store the data for when you're ready for it.
If you have one page, with multiple forms, you can use <input type='hidden' /> fields to hold the data until you're ready for it (it will be stored in $_POST each time you submit the form).
Then, when you're ready, pull the info out of the $_SESSION or $_POST data and run your query.
For the $_POST solution:
<form action='' method='post' >
<input type='hidden' name='data1'
value="<? if(isset($_POST['data1'])) { echo $_POST['data1']; } ?>"
<input type='hidden' name='data2'
value="<? if(isset($_POST['data2'])) { echo $_POST['data2']; } ?>"
<input type='hidden' name='data3'
value="<? if(isset($_POST['data3'])) { echo $_POST['data3']; } ?>"
</form>
<?
if(isset($_POST['data1'] && isset($_POST['data2'] && isset($_POST['data3']) {
//Run your query, echo results
}
?>