Using Form Field to Search Php Associative Array - php

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.

Related

How to allow user to add multiple values to array with php?

I have this php file that allows a user to enter their favorite music artist. My program puts the entered artist in a variable called "art" and then adds it to an array called "artist". Then it displays the array in a bullet list. But the program as it is only allows one value to be in the array. When the user enters another artist, it overwrites the one that is already in the array. For example, the user writes "bob" as their favorite artist and presses submit. The program displays bob, but when you go to put in another artist, "tess", bob is gone and only tess is diplayed. How do i fix this?
Here is the code: (Don't mind the commented out echo, it was a test to see if the entered value was being assigned to the variable.)
<h1> My Favorite Artist </h1>
<form method='POST'>
<h3>Please enter your favorite artist</h3>
<input type="text" name="artist">
<input type="submit" value="Submit Artist">
</form>
<?php
$art = $_POST['artist'];
//echo "<h3> This $art </h3>";
$artist = array();
array_push($artist, $art);
foreach ($artist as $a)
{
echo "<li>$a</li>";
}
?>
You can try by creating a session of array and then print it like this.
<?php
session_start();
?>
<h1> My Favorite Artist </h1>
<form method='POST'>
<h3>Please enter your favorite artist</h3>
<input type="text" name="artist">
<input type="submit" value="Submit Artist">
</form>
<?php
if(isset($_POST['artist']))
{
$art = $_POST['artist'];
//echo "<h3> This $art </h3>";
if(empty($_SESSION['artist']))
{
$_SESSION['artist'] = array();
}
array_push($_SESSION['artist'], $art);
$arry=$_SESSION['artist'];
if(!empty($arry))
{
foreach ($arry as $a)
{
echo "<li>$a</li>";
}
}
}

passing two values (one from text, one hidden) using html and php

I really struggle here and I spent much time on a solution but it seems that I missing something here.
So I have one page that I have 2 values:
$semesterID = $_GET['semesterID'];
$semesterID_old = $semesterID;
I do this as I want to pass 2 values on my next page. I am trying to do that with this:
<form action=ed_semester_v2.php method="post">
<div id="name">
<h2 class="name">Semester ID</h2>
<input class="subjectname" type="text" name="sem_id" id="sem_id" value= "<?php echo $semesterID; ?> " /> <br>
</div>
<input type="hidden" name="semesterID_old" value= "<?php $semesterID_old; ?>"/>
<button type="submit" value="Submit" name="submit">SAVE CHANGES</button>
</form>
The one $semesterID pass fine to the next page but the semesterID_old no. Just to clarify that the semesterid might change by the user and that's ok.
In my next page, I use this code:
if(isset($_POST['submit'])) {
$first_name=$_POST['sem_id'];
$last_name=$_POST['sem_name'];
$semesterID_old= $_POST['semesterID_old'];
if (empty($last_name)) {
echo "Name is empty";
} else {
$query = "UPDATE semesters SET name = '$last_name' where semesterid='$first_name'";
}
if (!mysqli_query($dbconnect, $query)) {
die('An error occurred when submitting your review.');
} else {
// echo "Thanks for your review.";
}
}
echo $first_name;
echo $semesterID_old;
First_name is fine but semesterID_old says that's undefined.
Any help would be much appreciated.
Just change echo semesterID_old; to echo $semesterID_old;

PHP multiple variables in a form

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>

Form to PHP_SELF but does not pass post values

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

Add variable into (specify text field) on the previous page

I have been looking for a way to add the information (string) from a variable in the previous page.
As far as I know this should be possible using javascript somehow.
New one couldn't get the old one to work properly..
<script type="text/javascript">
function newPopup(url) {
popupWindow = window.open(
url,'popUpWindow','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
Armory Avatar
I have that piece of code that opens the link into a new popup window(which remembers the url of the previous page).
In this window people can insert some information about there WoW character and the realm this character is on. After they do this and hit submit the site displays the url for the avatar retrieved from the blizzard armory.
http://eu.battle.net/static-render/eu/(imagepath)
Code for the popup page: Updated this current code (7-4-2012)
<?php
if (!isset($_POST['submit'])) {
?>
<!-- The fill in form -->
<html>
<head>
<title>Armory Avatar</title>
</head>
<body>
<form method="post" action="<?php echo $PHP_SELF;?>">
Character Name:<input type="text" size="12" maxlength="50" name="cname"><br />
Realm Name:
<select name="rname">
<optgroup label="English Realms">
<option value="aerie-peak">Aerie-Peak</option>
<option value="agamaggan">Agamaggan</option>
<option value="aggramar">Aggramar</option>
etc etc etc.
</optgroup>
</select><br />
<input type="submit" value="submit" name="submit">
</form>
<?php
} else { //If form is submitted execute this
$charname = $_POST["cname"]; //input character name
$realmname = $_POST["rname"]; //input realm name
$charurl = urlencode(utf8_encode($charname)); //prepares character name for url usage
$realmurl = 'http://eu.battle.net/api/wow/character/'.$realmname.'/'; //combines the basic url link with the realm name
$toon = $realmurl.$charurl; //adds the charactername behind the realm url
$data = #file_get_contents($toon); //retrieves the data from the armory api
if ($data) {
// if armory data is found execute this
$obj = json_decode($data); //converts the data from json to be used in the php code ?>
<img src='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> </img><br /> <?php //Is url link to image
$armoryname = utf8_decode($obj->name); //makes the name readable again
echo "Name: " . $armoryname . "<br />"; //character name
echo "Level: " . $obj->level . "<br />"; //character level
echo "Achievement Points : " . $obj->achievementPoints . "<br />"; //Achievement Points
if ( $obj->gender == 1 ){ //Deteremines the gender of the character
echo "Gender : Female <br />" ; //displays gender as female
}else{
echo "Gender : Male <br />" ; //dispalays gender as male
}
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
?>
Image: <a href='http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?>'> http://eu.battle.net/static-render/eu/<?php echo $obj->thumbnail; ?></a><br />
<!--Button submit code-->
<script type="text/javascript">
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
</script>
<input> <!-- The button here -->
<?php
}
else { // if armory data is not found execute this ?>
error code stuf
}
}
?>
Now i need this line of code:
$image = "http://eu.battle.net/static-render/eu/".$obj->thumbnail;
To be returned when the window is closed or simply by hitting another submit button(prefered to happen on close over button). And when either of those happen it needs to insert this into this string:
<input type="text" class="textbox" name="avatarurl" size="25" maxlength="100" value="{$avatarurl}" /></td>
The texbox called avatarurl.
Hopefully any of you know how to modify or create a javascript that does this for you. Since my php is already severely limited and my javascript knowledge is next to none.
You need to modify the way you're closing your pop-up window. Try something like this:
// When a BUTTON with the class name 'cancel_link'
// is clicked, it activates the following
$('button.cancel_link').click(function() {
// Change the value of the input with an ID of 'avatarurl'
// with the dynamic value given to you by the external JSON link
window.opener.getElementById('avatarurl').value = '<?php echo $image; ?>';
});
You need to make sure your closing link has cancel_link as its class name, and that your input element in your parent document has an id of avatarurl.
So after searching trying and thanks to #Jamie i knew where to look.
I found http://www.codingforums.com/showthread.php?t=213298
And this was finally the thing that worked.
On the php page to open it i added:
<script type="text/javascript">
function open_pop(){
window.open('armory.php','AvatarArmory','height=510,width=350,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no,status=yes')
}
</script>
<html>
.....
<input type="button" value = "OpenArmory" onClick="open_pop()" />
And added id="blogbox" to the input for the textbox.
<input type="text" class="textbox" name="avatarurl" size="45" value="{$avatarurl}" id="blogbox"/>
On the armory.php page i added this button with the javascrip function:
<script type="text/javascript">
function pops(avatar){
textcontent=opener.document.getElementById("blogbox").value;
opener.document.getElementById("blogbox").value = textcontent + " " + avatar;
}
</script>
<input type="button" value = "Insert Avatar.." onClick="pops('<?php echo $image; ?>');window.close()" />
And that worked perfectly.
Thank you jamie for the help.

Categories