Get option value AND text with PHP - php

Let's say I have a HTML form:
USA
CDN
And I select option 1 (USA)
Then a php page
Ok, duh, works fine and echo's "1"
How can I display "USA" as well? So in essence, I want to pass along the option's TEXT also. How could I do this?

You would either need to change the option value on the HTML page to be the text you want displayed (poses a XSS security hazard) or on the page that's displaying the text, you'd need an array where all the values match with the forum input.
Ex:
$names[1] = "USA"; $names[2] = "CDN";
Then when you want to display it, you'd call $names[$selection] to output the text.
Another option you can consider is using javascript to update a hidden HTML element on the submitting page when the user makes their selection (using onUpdate). This information would be passed along with the submitted form data. Not the most secure or reliable of options, but an option nonetheless.

The client's browser will not post back anything beyond the form element's name and value - you would have to incorporate additional form fields and Javascript (or change the element's value) to post "USA".

I suggest having a copy of the same data structure you used to print the form.
For example, if you were to do it all in one PHP page...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $key=>$country){?>
<option value='<?php echo $key;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=(int)$_POST['country'];
if(!isset($countries[$chosen])){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $countries[$chosen];?></div>
<?php }
Another option is to ditch the numeric value altogether, and just use the country name as the value of the option. However, for verification, you'll still want the list of values. Check the differences in this example...
<?php
$countries=array('USA','CDN');
?>
<form action='?' method='post'>
<select name='country'><?php
foreach($countries as $country){?>
<option value='<?php echo $country;?>'><?php echo $country;?></option>
<?php
} ?>
</select>
<input type='submit'>
</form>
<?php
if(isset($_POST['country'])){
$chosen=preg_replace('/[^\w]/','',$_POST['country']);//this isn't strictly necessary, since the next line checks if the value is in your original array - but filtering input is a good habit!
if(!in_array($_POST['country'],$countries)){?>Unknown country selection, wtf<?php exit; }?>
<div style='margin-top:20px;'>You selected <?php echo $chosen;?></div>
<?php }

Related

Using GET with a form

So I have a form which has a drop down list, when the submit button is pressed the script task4.php is called. My problem is that I can use the whole option that is selected, however I only need the tid. How do I get just the tid and use it task4.php?
<form action="task4.php" method="get">
<select>
<?php
foreach($results as $row) {
echo "<option>".$row[tid].", ".$row[category].", ".$row[division].", ".$row[clubID].", ".$row[name]."</option>";
}
?>
</select>
<input type ="submit" value="Submit">
</form>
This is what I've got in task 4 and it isn't working:
if (isset($_GET['tid'])) {
$tid = $_GET['tid'];
}
It's possible (perhaps even necessary) that in the absence of a value the browser is sending the text contents of the selected option with the form data.
Just give the option a value:
echo "<option value=\"".$row[tid]."\">" ...
Additionally, that select should really have a name (I don't even see how it could have worked without one):
<select name="tid">

Handling session value in select box FORM and PHP

I have a form and table like this.
What I'm trying to do is - If the select box is selected with a value, it is stored in session on submit(post) and i would like to retain the session value in select box.
If there is session value, it will display the session value in select box, else it will display all.
The below case is not working in my case.
What the below code do is - first time it doesn't set the session value. If I submit again(second time) the session is stored with the first value(first submit value) and it goes on like this.
Hope this question is answerable.
EDITED:
<?php
session_start();
if($_POST){
$_SESSION['book_id'] = $_POST['book_id'];
?>
<table class="table table-bordered" cellpadding="0" cellspacing="0" border="0">
My Table Content
</table>
<?php } ?>
<form method="post">
<?php print_r($_SESSION); ?>
<select name="book_id" class="form-control">
<option value="0">Select Book</option>
<?php while($row=mysql_fetch_array($book_query)){?>
<option <?php if(isset($_SESSION['book_id']) && $row['book_id'] == $_SESSION['book_id']) echo 'selected="selected"'; ?> value="<?php echo $row['book_id'];?>"><?php echo $row['book_name']; ?></option>
<?php }?>
</select>
<input type="submit" value="submit">
</form>
EDIT:
I have print_r for the session value.
What happens is - When I submit the form first time, the session value is empty.
When I submit it second time, the first submit value is stored in session, and it goes on.
Thanks,
Kimz
A few notes:
It seems you are mixing up book_id and book_name.
Also, you don't seem to submit a "book_name" in your form.
The "if($_POST)"-block is executed when the page loads, and not when the form is sent. So essentially, you first try to select something by a value in your session, and then afterwards store said value into your session.
First of all make sure you have session_start() included somewhere.
Secondly, try changing your IF on the options to this:
<?php if(isset($_SESSION['book_id']) && $row['book_id'] == $_SESSION['book_id']) echo 'selected="selected"'; ?>
Notice the isset. Without that on page load you are likely to get a PHP undefined index error.
Finally, try placing the 'if ($_POST) {}' before the form is displayed, so the session gets set before the form is displayed. Currently you wont see any changes until you refresh the page again, this is because the form is being rendered and then the session is set from the POST data afterwards.

How do I retrieve a selected value from a dynamically selection box

I would like to know how to retrieve a selected value from a dynamically selection box. If I get the selected value then I will store it into another variable that is located in another php file. This variable will help me in a sql query in postgresql.
//First php file
<form name="boton_alta_soniador" action="dar_alta_soniador.php" method="POST" autocomplete="off">
<div class="text-field">
Nombre de la asociacion
<? $strconn="dbname=postgres port=5432 host=127.0.0.1 user=xxx password=xxx";
$conn=pg_Connect($strconn);
$consulta="Select n_asociacion from asociacion";
$result=pg_query($conn,$consulta);
while($results [] =pg_fetch_object($result));
array_pop($results);?>
<select name="asociacion_seleccion" id="i_clave_asociacion">
<?php foreach ( $results as $option ) : ?>
<option value="<?php echo $option->i_clave_asociacion; ?>"><?php echo $option->n_asociacion; ?></option>
<?php endforeach; ?>
</select>
</div>
</form>
This is just the dynamically selection box. Then I want to store the selected value in this variable:
$ingresaAsociacion = pg_escape_string($_POST['asociacion_seleccion']);
So I can query the following statement:
$conocerIDasociacion = "SELECT N_ASOCIACION FROM ASOCIACION WHERE I_CLAVE_ASOCIACION='$ingresaAsociacion'";
I didn't want to use jQuery because the whole system is almost entirely made in PHP and HTML.
Please, any help is welcome and I'm all ears to everyone.
Cheers!
Looks like you're missing a Submit button.
You do not have to use AJAX at all, nor jQuery. You can submit your form and process the selection value as you see fit.
The selected value in the select Tag will be sent to dar_alta_soniador.php, and that file will process that data, using the exact code you wrote:
$_POST['asociacion_seleccion']
So, in dar_alta_soniador.php you will write that code:
$ingresaAsociacion = pg_escape_string($_POST['asociacion_seleccion']);
And then perform the query. You do not even have to worry about sending the data around in a session variable, POST does it for you already.
So everything should be OK in your code, or I may have misunderstood your question. Do you have an error message or get some inappropriate behavior?
Maybe the submit button is missing? I use a code like this:
For the select tag:
<div class="controls">
<select name="list_name">
<option>List</option>
<?php
foreach ($nucleos as $inner_array) {
$out = "<option>" . $inner_array['name'] . "</option>";
echo $out;
}
?>
</select>
</div>
And for the Submit button:
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Confirm</button>
<br/>
</div>
</div>
</form>
I am using bootstrap here for style, HTML and CSS. Nothing more.
Best wishes,
I found another solution:
<? $strconn="dbname=postgres port=5432 host=127.0.0.1 user=xxxx password=xxxx";
$conn=pg_Connect($strconn);
$consulta="Select n_asociacion from asociacion";
$result=pg_query($conn,$consulta);?>
<select name="asociacion_seleccion" id="i_clave_asociacion">
<?php
while($row=pg_fetch_assoc($result))
{echo "<option>{$row['n_asociacion']}</option>";}?>
</select>
The point is, whenever the user selects an option from the dyamically selection box, the value of the selection box is known if we call the value with pg_escape_string($_POST['NAME OF YOUR SELECTION BOX']);.
Thanks to all for your collaboration,my problem was resolved.

One submit button to send form data to one PHP destination OR another

I' new to HTML and PHP and was wondering if anyone out there could help me with a question... I'm trying to code a form that submits a selection from one menu OR another and, depending on which is chosen sends the data to one of two different PHP pages.
<form id="form1" method="post" action="">
<label for="SubjectID">Text Books by Subject</label>
</p>
<p>
<select "name="SubjectID" id="SubjectID">
<?php do { ?>
<option value="<?php echo $row_rsSubject['SubjectID']?>"><?php echo $row_rsSubject['SubjectName']?></option>
<?php } while ($row_rsSubject = mysql_fetch_assoc($rsSubject));
$rows = mysql_num_rows($rsSubject);
if($rows > 0) {
mysql_data_seek($rsSubject, 0);
$row_rsSubject = mysql_fetch_assoc($rsSubject);
} ?>
</select>
</p>
<p>
——— OR ———
</p>
<p>
<select name="CourseID" id="CourseID">
<?php do { ?>
<option value="<?php echo $row_rsCourse['CourseID']?>"><?php echo $row_rsCourse['CourseID']?></option>
<?php } while ($row_rsCourse = mysql_fetch_assoc($rsCourse));
$rows = mysql_num_rows($rsCourse);
if($rows > 0) {
mysql_data_seek($rsCourse, 0);
$row_rsCourse = mysql_fetch_assoc($rsCourse);
} ?>
</select>
</p>
<p>
<label for="CourseID">Text Books by Course</label>
</form>
So, the action should be (depending on which menu the user selects from) that the form submits to either subject.php or course.php, and I can't figure out how to do that with a single submit button. Can anyone help me?
first set onchange event to select:
<select name="CourseID" id="CourseID" onchange='myFunc(this)'>
Then:
<script>
function myFunc(element){
// set the form action depends on option chosen
// element.setAttribute('action', 'yourPageLink' );
}
</script>
You could update the action attribute with javascript when the user changes his selection, directing him to the relevant page.
Otherwise, why not submit to a single function and depending on the users selection call the relevant function?
Honestly I would use jquery's $.post to do this. To the best of my knowledge you can't really do that with straight html, and php is executed before the page loads so that's no help. With JQuery you could set an action to the button to call a function. Then your function could check the value of the select and pass the proper url to the $.post function.
You can read about that particular jquery function here: http://api.jquery.com/jQuery.post/
If you're not familiar with JQuery it's really easy to use with just a bit of reading if you're good with JavaScript.
Why not have a radio button in the form whose posted form value is processed by a central PHP form handler? That way, depending on what is entered on the radio button, you can process the request as necessary.
This might not be the answer you are looking for, but I am not clear if you want the user to be able to alter the destination or what.

How do I call up values in PHP for user input in forms (radio buttons and selects)

Ok so my admin sets to edit a book which was created. I know how to bring in the values that were initially entered via a simple text field like 'bookname'. On the edit book page the book name field stores the currently assigned 'bookname' in the field (which is what I want! :) )
However I have other field types like selects and radio button entries...I'm having trouble calling in the already set value when the book was created.
For example, there is a 'booklevel' field, which I have set as radio button entries as; Hard, Normal, and Easy. When the user goes to edit the book, I'm not too sure on how to have the current value drawn up (its stored as text) and the radio button being checked. I.e. 'Normal' is checked if this is what was set when the book was created. So far I have this as the code for the adding book level:
<label>Book Level:</label> <label for="booklevel1" class="radio">Hard
<input type="radio" name="booklevel" id="booklevel1"
value="<?php echo 'Hard'; if (isset($_POST['booklevel'])); ?>"></label>
<label for="booklevel2" class="radio">Medium<input type="radio" name="booklevel"
id="booklevel2"
value="<?php echo 'Normal'; if (isset($_POST['booklevel'])); ?>"></label>
<label for="booklevel" class="radio">Low<input type="radio" name="booklevel"
id="booklevel3"
value="<?php echo 'Easy'; if (isset($_POST['booklevel'])); ?>"></label>
This all works fine by the way when the user adds the book... But does anyone know how in my update book form, I can draw the value of what level has been set, and have the box checked?? To draw up the values in the text fields, I'm simply using:
<?php echo $row['bookname']?>
I also noticed a small issue when I call up the values for my Select options. I have the drop down select field display the currently set user (to read the book!), however, the drop down menu again displays the user in the list available options to select - basically meaning 2 of the same names appear in the list! Is there a way to eliminate the value of the SELECTED option? So far my setup for this is like:
<select name="user_id" id="user_id">
<option value="<?php echo $row['user_id']?>" SELECTED><?php echo $row['fullname']?></option>
<?php
while($row = mysql_fetch_array($result))
{ ?> <option value="<?php echo $row['user_id']?>"><?php echo $row['name']?></option>
<?php } ?>
</select>
If anyone can help me I'll be very greatful. Sorry for the incredibly long question!! :)
For the radio buttons, simply add the attribute checked="true" if the current button's value matches the value you already have. For the dropdown, don't use the first option you have there, but instead use the same technique as the radio buttons, but with selected="true".
Check to see which string is stored in the DB (easy, normal, hard) and then set the checked field to 'checked'. For example:
<label>Book Level:</label> <label for="booklevel1" class="radio">Hard
<input type="radio" name="booklevel" id="booklevel1"
value="hard" <?php if($row['booklevel'] == 'hard') echo 'checked="checked"'; ?>></label>
As to the second part - you'll need to store the first value of $row['user_id'] in a temporary variable before entering the while loop. Then check each additional user_id you receive to determine whether it is equal. If it is, don't print its option. Like so:
<?php
$tmp = $row['user_id'];
while($row = mysql_fetch_array($result)) {
if($row['user_id'] != $tmp) {
echo '<option value="'.$row['user_id'].'">'.$row['name'].'</option>';
}
}
?>

Categories