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
Related
I am currently doing up a list of names that has signed up for a activity which is then needed to go through another selection process and to be put into the database. I have currently done the getting and displaying of names from the people that has signed up.
However, I am not too sure on the process of how I can get those checked which is being selected in the selection process.
This is currently the codes that I have done to get and display the names of the people who have signed up. Upon clicking submit, it would go to another page which would then process, get those checked and marked as 1 or true to the database (MySQL) or either set as 0 or false if it has not been checked.
<?php
if ($totalShortlist > 0) {
?>
<?php
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<form id="selectionProcess" action = "doShortlistProcess.php?id=<?php echo $id ?>" method = "post">
<fieldset data-role="controlgroup">
<label><input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/><?php echo $firstName; ?> <?php echo $lastName; ?></label>
</fieldset>
<?php
}
?>
<input type="submit" class="btnSelect" data-theme="b" data-inline="true" name="shortlistCandidate" value="Submit Shortlisted Candidates"/>
</form>
<?php
}
// end for loop
else {
echo "No candidates to be shortlisted";
}
mysqli_close($link);
?>
The $id as shown is the brought over from the list of categories on the previous page, which allows to get all the names in that categories to be displayed.
Your code places the form in the wrong place compared to the while loop. The action also doesn't need you to compose a query string. Better code (careful, I've also cut out some presentation):
if ($totalShortlist > 0) {
?>
<form id="selectionProcess" action = "doShortlistProcess.php" method = "post">
<fieldset>
<?php
// use while loop to display a tick box for each item
while ($row = mysqli_fetch_assoc($result)) {
$firstName = $row['first_name'];
$lastName = $row['last_name'];
?>
<label>
<input type="checkbox" name="selectionProcess" id="selectionProcess" value="<?php echo $id ?>"/>
<?php echo $firstName; ?> <?php echo $lastName; ?>
</label>
<?php
} // end of while loop
?>
</fieldset>
<input type="submit"/>
</form>
<?php
} // end of shortlist > 0
I recommend you test this code using the GET method. It will show you what form the submission takes.
To process the result, you should use the list of responses, process it and turn it into one or more SQL statements.
An alternative would be to use an action for each checkbox, but then use ajax to a php page that would modify the status of single subscriber. The change would be made immediately as users click.
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>
Let me present my code first:
<?php include ('header.php'); ?>
<h3>Extra menu items , van eigen pagina's</h3>
<!-- zet menu onderdelen aan of uit -->
<?php
if ($_POST['submit'] == 'Verzenden') {
$checkbox_vals = $_POST['np_menu_active_post']; // This will pass the selected checkbox values as an array
//if(count($checkbox_vals) > 0) {
// Loop it and update the values in DB
foreach( $checkbox_vals as $key ){
$updatequery = "UPDATE custompage set np_menu_active = '$key'";
mysql_query($updatequery) or die("Couldn't get file list");
}
//}
?>
<meta HTTP-EQUIV="Refresh" CONTENT="0"; URL="<?php echo $_SERVER['PHP_SELF'];?>">
<?php
}
?>
<?php
$dbQuery_custom_toggle = "SELECT * ";
$dbQuery_custom_toggle .= "FROM custompage";
$result_custom_toggle = mysql_query($dbQuery_custom_toggle) or die("Couldn't get file list");
while($row = mysql_fetch_array($result_custom_toggle)) {
// $nptitel = $row['np_titel'];
// $nptekst = $row['np_tekst'];
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="hidden" name="np_menu_active_post[]" value="0" />
<?php echo $row['np_menu_titel'];?> <input type="checkbox" name="np_menu_active_post[]" value="1" <?php if($row['np_menu_active'] == "1"){echo 'checked="checked"';}?> /> <br />
<?php
}
?>
<input type="Submit" name="submit" value="Verzenden" class="btn-primary">
</form>
<!-- einde menu toggles -->
<br />
<br />
So im trying to make this form write the 1 value or 0 value based upon the checkboxed to the mysql db.
Its partly working, when i select the last checkbox, it checks all, and writes that to the db.
With the foreach loop you update your db in the same field with each checkbox, so the last checkbox is the only thing that is left.
Depending on the desired result, you need to differ the column (so np_menu_active) for each checkbox, or need to add a WHERE condition (as Rick said) to differ the row.
E.g. If you would like to save the checkbox settings for multiple users, you would create a column for each checkbox and a row for each user.
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.
Code:
<?php
echo "<h1>Testing your Trivia</h1>";
$ages['1943'] = "Casablanca";
$ages['1956'] = "Around The World in 80 Days";
$ages['1970'] = "Patton";
$ages['1977'] = "Annie Hall";
$ages['1981'] = "Chariots of Fire";
$ages['1990'] = "Dances With Wolves";
$ages['2005'] = "Crash";
$ages['2006'] = "The Departed";
echo "Give the year below won academy award<br>";
echo "<Strong>Movie: </strong> <input type='text' name='' id='' readonly='readonly' /><br>";
echo "<Strong>Year it Won the Oscar: </Strong> <form method='get'><input type='text' name='year' /></form><input type='submit' /> ";
echo '<pre>';
foreach( $ages as $key => $value){
print_r("Year: $key, Title: $value <br />");
}
echo '</pre>';
if(isset($_GET['year']))
{
if(array_key_exists($_GET['year'], $ages))
{
echo "<h2>" . $ages[$_GET['year']] . "</h2>";
}
else
{
echo 'Cannot find data';
}
}
?>
Basically trying to have it setup where I can get the movie input to choose a random title and display it in the input field for "movie", then a user has to guess the year it was made. If their too high, it shows a page saying that, if too low it shows an error as well.
I feel like I need to add in another If/Else for if high or too low. Anyone?
Thanks!!
Is there a reason your array keys are strings? It seems like it would make sense in this case for them to be integers.
<?php
$ages['1977'] = "Annie Hall";
$ages['1956'] = "Around The World in 80 Days";
$ages['1990'] = "Dances With Wolves";
$ages['2006'] = "The Departed";
$ages['2005'] = "Crash";
$ages['1943'] = "Casablanca";
$ages['1981'] = "Chariots of Fire";
$ages['1970'] = "Patton";
if(isset($_GET['year']))
{
if(array_key_exists($_GET['year'], $ages))
{
echo $ages[$_GET['year']];
}
else
{
echo 'Cannot find data';
}
}
?>
<form method="GET">
<input type="text" name="year" value="1984" />
<input type="submit" />
</form>
If the user is submitting, say, a value from a dropdown menu/list of radio buttons, you could check to see if the $ages array has that year set, and if not, display a default message:
$year = $_GET['year'];
echo isset($ages[$year]) ? $ages[$year] : 'DOES NOT COMPUTE';
Expanded Edit
MVC men will likely put out a hit on me for saying this (if they haven't already), but I like to keep this kind of thing self-contained. That means a page (say, index.php) that looks generally like this:
<?php
// All of your PHP goes here.
?>
<!DOCTYPE html>
<!-- All of your HTML goes here. -->
I'll start with HTML. You'll want a form, like so:
<form action="" method="get">
<div>
<label>Movie Year: <input type="text" name="year" />
<input type="submit" value="Look Up Movie" />
</div>
</form>
Note that the form's action is left blank. That means that the form will be submitted to the current page. That's where the PHP at the top of your document comes into play.
You'll first want to initialize your array of years and titles:
$ages = array(
'1977' => 'Annie Hall',
// ...
'1970' => 'Patton'
);
Then you check to see if the user submitted the form:
if (isset($_GET['year'])) {
$year = $_GET['year'];
$message = isset($ages[$year]) ? 'The film for that year is called '.$ages[$year].'.' : 'There is no film for that year.';
}
This sets the variable $message to some text that you want to display to the user.
Now we make one last jump back to the HTML part of your document, just above the form:
<?php
if (!empty($message)) {
echo '<p>', $message, '</p><p>Want to go again?</p>';
}
?>
And there you have it, a searchable array of movie titles, organized by year.