PHP Loop assistance - php

I am trying to find out online how to make a form loop based on a dropdown value. So for example, If the dropdown is selected on 2, it will loop a preset form twice, if the option was 3 it would display the form 3 times. This would be helpful because I am trying to get those forms into an array and then use the array to send to phpmyadmin etc.
Another question is how would I be able to get the value of each form being displayed, unless I can have the code differentiate between the forms, it might just see the values as one instead of two separate if that makes sense.
<html>
<?php
session_start();
?>
<?php include 'AdminHeader.php' ?>
<?php include '../Includes/dbh.inc.php' ?>
<body bgcolor="grey">
<div class="main">
<form method="POST">
<select name="RaceNum">
<option> Number of Horses </option>
<option> 1 </option>
<option> 2 </option>
</select><br />
Horse Number: <input type="text" name="HorseNumber"><br/>
Horse Name: <input type="text" name="HorseName">
<button type="Submit" name="submit"> Submit </button>
</form>
<?php
if(isset($_POST['submit'])) {
$RaceNum = $_POST['RaceNum'];
$HorseNumber = $_POST['HorseNumber'];
$HorseName = $_POST ['HorseName'];
while($RaceNum < 2){
$stack = array(
1 => array( 'Horse Number' => $HorseNumber, 'Horse Name' => $HorseName )
);
echo "<pre>";
print_r($stack);
echo "</pre>";
}
}
?>

Related

How to set the number of items in an array based on html form input?

I am working on creating a PHP file and one thing that I'd like to do is have an array (Example 1). From what I understand, and Array is like a list, and I want to also input items on the list (Example 2). But the number of items in the array need to be determined by a number, inputted via a HTML form (Example 3).
Example 1:
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
</body>
</html>
</code>
Example 2:
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
array_push($a,"$_POST["color3"]","$_POST["color4"]");
print_r($a);
?>
</body>
</html>
Example 3.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="color3"></li>
<li><input type="text" name="color4"></li>
</form>
</ol>
EDIT:
I hope this is all formatted correctly, and you understand the question.
To reiterate: The first page is blank with just a form; single input box, where you type in any number ( X ).
The Second page has the same line repeated over and over (depending on the number X from the previous page), it's line is:
<li><input type="text" name="color Y"></li>
Y should count from 1 up infinitely until X is reached.
The Last page prints it all in a list (array?).
For Example: On the first page we enter the number 3.
On the second page we have 3 boxes for inputting the names of our chosen colors: Red, Blue, Yellow.
On the last page we are shown a list of our three colors: Red, blue and yellow.
Hope this helps.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="data['color3']"></li>
<li><input type="text" name="data['color4']"></li>
</form>
</ol>
then in the finished.php
$_POST['data'];
print_r($_POST);//print out the whole post
print_r($_POST['data']); //print out only the data array
I think I got it what you want (after reading more than once). Let me know if I understood correctly. Let's assume you're using 3 different files (as you wrote in your question).
file1.php (a simple form with 1 input and 1 submit button):
<form action="file2.php" method="post">
<input type="text" name="amount" placeholder="The amount of elements">
<input type="submit" value="Enter">
</form>
file2.php (check if $_POST and the value is an integer):
if (!empty($_POST['amount'])) {
if (!is_int($_POST['amount'])) {
exit('Not an integer');
}
?>
<form action="file3.php" method="post">
<?php
for ($i = 0; $i < $_POST['amount']; $i++) {
echo '<input type="text" name="colors[]" placeholder="Enter color name"><br>';
}
?>
<input type="submit" value="Done">
</form>
<?php
} else {
exit('Only $_POST method is allowed.');
}
file3.php (get all results and store an array in variable):
if (!empty($_POST)) {
$colors = $_POST['colors'];
foreach ($colors as $color => $value) {
echo '<li>'.$value.'</li>';
}
exit;
} else {
exit('Only $_POST method is allowed.');
}
We can add some more security (like checking if it's not empty, etc.), but I'm adding just basic things.

Keep select list on reload

I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.

How to create a PHP dropdown list

I am trying to build a php contact form with a dropdown list of values, say "A", "B" and "C", that fits the code structure below.
As well, I would like to call this form from a link on another page, and have the value of the dropdown list automatically populated with the passed-in parameter. For example, if the link is "...?val=B", I'd like the dropdown list to automatically set to "B".
I have code below that works for an email field. What does the code look like for a dropdown list?
It's been a long while since I've coded PHP, so any help is appreciated.
<div class="input-field">
<div>
<?php _e('Email','circles'); echo ' <span>('; _e('required','circles'); echo ')</span>'; ?>
</div>
<div class='input-style dlight-grey sc-input'>
<input type="email" name="form_email" size="20" value="<?php echo $form_email; ?>" />
</div>
</div>
Suppose you store options to a html select element(dropdown list) in array $ops
<form>
<select name='foo'>
<?php
$val = $_GET['val'];
while($option = next($ops)){
if ($option == $val){
echo "<option value=$option selected='selected'>$option</option";
else
echo "<option value=$option>$option</option>";
}
?>
</select>
<form>
Alternatively, you can use Javascript to add 'selected' attribute to the option equals to $_GET['val'], see .attr()

PHP Form - Highlight multiple selection for SQL query

I'm trying to keep multiple options selected in a dropdown form after being submitted but I can't get it to work. The options don't stay selected. I've seen answers for this using foreach() (Highlighting multiple selections on a form after submitting), however my data comes from a SQL query so I believe I need to use while() to loop through the rows. Any thoughts?
$id7 = $_REQUEST['id7'];// Interest Level
<?php
$getParameter_sql4 = 'SELECT Funds.[Interest Level] FROM Funds GROUP BY Funds.[Interest Level] ORDER BY Funds.[Interest Level]';
$getParameter4 = sqlsrv_query($conn,$getParameter_sql4);
?>
<form action="/Reports/FundStatistics.php" method="get">
<select name="id7[]" multiple size="4">
<?php while ($row4 = sqlsrv_fetch_array($getParameter4, SQLSRV_FETCH_ASSOC)) { ?>
<option <?php if (in_array($row4['Interest Level'],$id7)) { echo 'selected="selected"';}?> value="'<?php echo $row4['Interest Level']; ?>'"><?php echo $row4['Interest Level']; ?></option><?php }?>
</select>
<input type="submit" VALUE="Update" /></form>

Decide which hidden input value gets passed

I built a custom form for search filtering on my site. I'm using hidden input fields to decide what type of search filter was selected. The value gets passed and I check on my search page what the value was, and then direct to the correct search results page like so:
<?php
$search_refer = $_GET['search_type'];
if($search_refer == 'members') {
load_template(TEMPLATEPATH . '/search-members.php');
} else if($search_refer == 'event') {
load_template(TEMPLATEPATH . '/search-member-event.php');
} else {
load_template(TEMPLATEPATH . '/search-site.php');
}
?>
Here are the two fields in HTML/PHP
<div class="state"> // Sorting by user State
<input type="hidden" name="search_type" value="members">
<select id="stateDrop" name="state">
<option value="">State</option>
<?php
foreach($states as $state) {
echo '<option value="'.$state.'">'.$state.'</option>';
}
?>
</select>
</div>
<div class="sort-event"> // Sorting by an Event
<input type="hidden" name="search_type" value="event">
<select id="eventDrop" name="event">
<option value="">Event</option>
<?php
$args = array(
'post_type' => 'events',
'order' => 'ASC'
);
$eQuery = new WP_Query( $args );
while( $eQuery->have_posts() ) : $eQuery->the_post();
echo '<option value="'.$eQuery->post->post_title.'">'.$eQuery->post->post_title.'</option>';
endwhile;
wp_reset_query();
?>
</select>
</div>
Both have the name search_type as a hidden name, but the values are different. members vs event. My problem is when you click on the submit button, the value being received is always the last hidden input value. e.g. event.
Is there a way to decide which field was chosen so that I can then direct the search results to the correct page. (the search pages pull in different information based on the search).
Thanks,
As you have two inputs with the same name, only one of them will ever be set to the server.
If you want them to use the same name you're going to need to use POST and two forms, which would require two separate submit buttons but go to the same page. This way you can submit the desired form based on the filter.
<form action="yourpage.php" method="post">
<input type="hidden" name="search_value" value="members"/>
... member stuff
<input type="submit" value="Filter Members"/>
</form>
<form action="yourpage.php" method="post">
<input type="hidden" name="search_value" value="event"/>
... event stuff
<input type="submit" value="Filter Events"/>
</form>
Or you could use an input type of a radio button, as that supports having the same name as only one value can be selected at once.
Event: <input type="radio" name="search_type" value="event"/>
Members: <input type="radio" name="search_type" value="members"/>
// Then in PHP $_POST["search_type"] will hold the selected value.
If you wish to stick with GET, you could use JavaScript to set the value of a single hidden element before the user clicks the link.

Categories