How to wipe a search query in PHP? - php

I have a search form that uses Javascript to change the input method depending on what's selected. So if you have "Name" selected you get a text box, but if you have "Rating" selected you get a drop-down list from 1-5.
<form method="GET" action="results_sample.php">
<p>Search by: <!-- Dropdown list allows users to search by different elements -->
<select id="searchtype" name="searchtype" onchange="changeview()"> <!-- onchange calls changeview() every time the dropdown value is changed. Allows ratings to be seen -->
<option value="School">School</option>
<option value="Name">Name</option>
<option value="Rating">Rating</option>
<option value="Class Location">Class Location</option>
<option value="Subject">Subject</option>
</select>
</p>
<span id="standard" style="display:inline">Search Query: <input type="text" name="query"></span>
<span id="locationsearch" style="display:none"> (Longitude-Lattitude pair) <input type="number" id="longitude" step="any"> - <input type="number" id="latitude" step="any"> </span>
<span id="ratevalue" style="display:none"> Choose rating:
<select id="ratings">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
</span>
<p><input type="submit"></p>
</form>
The relevant code in results_sample.php is:
<?php
if (isset($_GET['searchtype'])) {
if (!empty($_GET['query'])) {
$search = $_GET['query'];
} elseif (!empty($_GET['ratings'])) {
$search = $_GET['ratings'];
} elseif (!empty($_GET['longitude']) || isset($_GET['latitude'])) {
$search = 'more to come...';
}
echo '<p>Entries containing "', $search, '" in "', $_GET['searchtype'], '"</p>';
}
?>
I have two problems:
1) If I type text into the search query, then switch to ratings, and try to search by ratings, it still has the textbox invisible in the background, and uses that information instead.
2) If the textbox is empty and I want to search by Longitude-Latitude, Rating is still set at a default of 1 (invisible in the background) and it takes that value.

One option is to check $_GET['searchtype'] value and select another $_GET variable according to it, something like:
switch ($_GET['searchtype']) {
case 'Name':
$search = $_GET['query'];
break;
case 'Rating':
$search = $_GET['ratings'];
break;
case 'Class Location':
$search = 'other value';
break;
// add more cases as you wish
}
Other option can be using javascript to clear other fields' values when you change #searchtype but in this case select#ratings still will be sent to server.

Related

Having trouble validating the <select> element within a larger <form> element - it won’t return an error message

I’ve been building a series of webpages that allows for dynamic data manipulation (CRUD). The pages are built with HTML, CSS, and PHP.
At this stage of the project, my goal is to have the site return an error message if data is not entered into a particular field.
I've made a small sandbox for the problem.
At the top of the page, I included the following PHP logic to outline the variables and how the page will behave if data is entered into the form fields (or not entered):
$routeType = "";
$hasRouteType = false;
$routeTypeError = false;
if( isset($_POST["add"]) ) {
if( isset($_POST['route-type']) ) {
$routeType = $_POST['route-type'];
if($routeType) {
$hasRouteType = true;
} else {
$routeTypeError = "Please select a route type.";
}
}
}
I made a dropdown menu as one of the elements in the form as follows:
<form method='POST'>
<field>
<label>Route Type</label>
<select name="route-type" id="route-type">
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
<option value="interstate">Interstate</option>
<option value="stateRoute">State Route</option>
<?php if($routeTypeError) { ?>
<p class='error'><?=$routeTypeError?></p>
<?php } ?>
</select>
</field>
<form>
<button class='route-button' type="submit" name='add'>Add route</button>
At this stage, when the user doesn't choose anything from the dropdown, no error message is returned -- again, this is the goal of this stage of the project.
Steps I've tried to solve the problem so far (these didn't work)
I’ve tried changing the logic in the principal foreach statement.
if($routeType) {
$hasRouteType = true;
if($routeType != "") {
$hasRouteType = true;
I’ve tried changing the data type of the $routeType variable when it's initialized.
I’ve tried adding selected=“true” and disabled=“disabled” to the top element in the dropdown menu to make it the first thing that appears on the page — and also to make it impossible for the user to select it as an option from the menu.
<option value="" selected="true" disabled="disabled">What type of route is this?</option>
I've been told that "looping through the option elements" might be a possible solution, but I don't know how to implement this.
My goal is to have the error message "Please select a route type." returned if the user does not select anything from the dropdown menu.
Thanks very much for the help!
You need an option field with empty value and the required.
Solution with client-side check
<select name="route-type" id="route-type" required="required">
<option value="">What type of route is this?</option>
<option value="A" >Select A</option>
<option value="B" >Select B</option>
</select>
You don't need php for this.
Try to submit this without select a value and you will get an error message.
All html and javascript checks are just goodies, you always have to check all values ​​with php(when you use php) when you get them from a form.
Never trust any data and check every data you receive!
UPDATE:
Maybe this is a possible solution you looking for with php:
Solution with php check
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
If you wan't to check with the required option also on the client-side use:
<select name="route_type" required="required">
You can also build your option fields with a loop and use the values from the array.
Solution with php check and custom error message(javascript alert):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
echo "<script>alert('Please select type')</script>";
}
?>
<form method="post">
<select name="route_type">
<option value="">SELECT A TYPE</option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
Solution with php check and custom error message(php in option field):
<?php
$route_check = array(
'interstate'
,'stateRoute'
);
if(!in_array($_POST['route_type'] ?? '' , $route_check)){
if( ($_POST['SEND'] ?? '') === 'SEND'){
$MESSAGE = 'NO TYPE SELECTED';
}
else{
$MESSAGE = 'SELECT A TYPE';
}
?>
<form method="post">
<select name="route_type">
<option value=""><?php echo $MESSAGE; ?></option>
<option value="interstate">interstate</option>
<option value="stateRoute">stateRoute</option>
</select>
<input type="submit" name="SEND" value="SEND">
</form>
<?php
}
else{
echo "DO SOMETHING";
}
?>
This is just a small example of how it could work, of course you can further optimize and adapt the code

PHP form validation drop down, display "required" if user doesnt have an input. Prevent reset of the dropdown value

I need help with form validation. I can get it to work with text boxes but I am having trouble validating drop down lists.
I have included a part of my php code plus the code that is imbedded in the HTML
I am having trouble displaying the required text next to the drop down list. Also how would I display the user selected option if the user forgets to enter an input elsewhere on the form so it doesn't reset the dropdown field and show what the user had already had selected.
<?php
if(empty($_POST['title']))
{
$errors['title1'] = " Required";
}
<p>
?>
<label for="title" class="label"><font color="#040404">Title:</font></label>
<select name="title">
<option value="" selected="selected">Select title</option>
<option value ="Mr">Mr</option>
<option value ="Mrs">Mrs</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Dr">Dr</option>
</select>
</p>
Here is another approach, which assumes that your page loads in, and if the "title" select either has a selection or not. Again, it's just a suggestion to try out.
<select name="title">
<?php
$titles = array ('Mr', 'Mrs', 'Ms', 'Miss', 'Dr');
if (isset($_POST['title'])) {
echo '<option value="">Select title</option>';
$use_title = $_POST['title'];
} else {
// Selection not made, let "Select title" be selected.
echo '<option value="" selected="selected">Select title</option>';
$use_title = "";
}
//When selected before, it will append the selected attribute.
foreach ($titles as $ti) {
$selected_attr = ($ti == $use_title ? ' selected="selected"' : '');
echo sprintf(
'<option value="%s"%s>%s</option>'
$ti,
$selected_attr
$ti,
);
}
?>
</select>

Calculate total price of two books using PHP and HTML

I want to know what can be the way using php and html such that I am provided a dropdown of books, I need to select exactly two choices out of that drop down and then calculate sum of price of both the books.
Assuming I had hardcoded the Books say:
Book 1 - $5
Book 2 - $15
Book 3 - $50
I know with if it was to select only one book. But no idea for this one. Please help
Code :
<?php
if(isset($_POST['formSubmit']))
{
$varCurrentBook = $_POST['formBook'];
$errorMessage = "";
if(empty($varCurrentBook))
{
$errorMessage = "<li>You forgot to select a Book!</li>";
}
if($errorMessage != "")
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
else
{
switch($varCurrentBook)
{
//Can use here to find what option is clicked
}
exit();
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for='formBook'>Select a Book</label><br>
<select name="formBook">
<option value="0">Select a Book...</option>
<option value="15">The Secret</option>
<option value="10">The Fairy Tales</option>
<option value="5">All about words</option>
<option value="100">Pinaacle Studio</option>
<option value="120">Harry Potter</option>
<option value="200">Thinking in Java</option>
</select>
<input type="submit" name="formSubmit" value="Submit" />
</form>
You need to use a multiple select as:
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label for='formBook'>Select a Book</label><br>
<select name="formBook[]" multiple><!--The multiple attribute-->
<option value="0">Select a Book...</option>
<option value="15">The Secret</option>
<option value="10">The Fairy Tales</option>
<option value="5">All about words</option>
<option value="100">Pinaacle Studio</option>
<option value="120">Harry Potter</option>
<option value="200">Thinking in Java</option>
</select>
<input type="submit" name="formSubmit" value="Submit" />
</form>
Also note how I changed name from formBook to formBook[]. This changes $_POST['formBook'] to an array of options.
Then you can access it as:
<?php
foreach ($_POST['formBook'] as $names)
{
print "You have selected $names<br/>";
/*Your also need to change your code here accordingly.*/
}
?>
You have to use multiple select with jquery
see: HTML Multiselect Limit
<select name="formBook">
have to become:
<select name="formBook[]" multiple">
Then you can sum all selected elements
if(isset($_POST['formSubmit']))
{
$sum = array_sum($_POST['formBook']); // Sum of all selected elements
...
}
As ARBY answered correct you have to add the multiple attribute to your select element:
<select name="formBook" multiple>
This sends the value attribute. (E.g. 0 / 15 / 10)
So you can check if you have exactly two books like this:
//Check if the user has selected exactly two books
$formBooks = $_POST['formBook'];
if(count($formBooks) !== 2){
//TODO: return error message that user has to select two books
}
//Calculate the value
$result = array_sum($formBooks);
//TODO: return value

Insert value into database input or drop down menu

I have a form that a user can insert his/her level of education either by picking a value from a drop down menu or just typing some text. My code is simple:
<label for="education">Education: <input type="text" name="education"/> </label>
<select name="education">
<option value=""></option>
<option value = "Primary education" name="Primary education">Primary education</option>
<option value = "Secondary education" name="Secondary education">Secondary education</option>
<option value = "Bachelor" name="Bachelor">Bachelor</option>
<option value = "Master" name="Master">Master </option>
<option value = "Doctoral" name="Doctoral">Doctoral </option>
</select>
So i want to insert that value in a column called education in database. Using code above the value is inserted only when someone is picking a value from menu. Input text is not stored in database.
In your textbox part;
Change
<label for="education">Hobby: <input type="text" name="education"/> </label>
to
<label for="education">Hobby: <input type="text" name="education_text"/> </label>
Duplicate name causes your problem(select and textbox name are same). I have given education_text as an example, update it according to your needs. Do not forget to handle it backend with updated name.
On your backend;
$education = "";
if(!empty($_REQUEST["education_text"])) {
$education = $_REQUEST["education_text"];
} else if(!empty($_REQUEST["education"])) {
$education = $_REQUEST["education"];
} else {
die("Invalid education");
}
And use it in your query. You can change $_REQUEST to $_POST or $_GET according to your needs

PHP code to get selected text of a combo box

I have a combo box named "Make". In that combo box I'm loading vehicle manufacturer names. When I click SEARCH button I want to display the selected manufacturer name. Below is part of my HTML code.
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="submit" name="search" value="Search"/>
Below is my PHP code so far I've done.
<?php
if(isset($_POST['search']))
{
$maker = mysql_real_escape_string($_POST['Make']);
echo $maker;
}
?>
If I select Toyota from the combo box and press SEARCH button, I'm getting the answer as '2' . It means it gives me the value of the 'Toyota'. But I want to display the name 'Toyota'. How can I do that? Please help me ....
Try with this. You will get the select box value in $_POST['Make'] and name will get in $_POST['selected_text']
<form method="POST" >
<label for="Manufacturer"> Manufacturer : </label>
<select id="cmbMake" name="Make" onchange="document.getElementById('selected_text').value=this.options[this.selectedIndex].text">
<option value="0">Select Manufacturer</option>
<option value="1">--Any--</option>
<option value="2">Toyota</option>
<option value="3">Nissan</option>
</select>
<input type="hidden" name="selected_text" id="selected_text" value="" />
<input type="submit" name="search" value="Search"/>
</form>
<?php
if(isset($_POST['search']))
{
$makerValue = $_POST['Make']; // make value
$maker = mysql_real_escape_string($_POST['selected_text']); // get the selected text
echo $maker;
}
?>
Put whatever you want to send to PHP in the value attribute.
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="--Any--">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You can also omit the value attribute. It defaults to using the text.
If you don't want to change the HTML, you can put an array in your PHP to translate the values:
$makes = array(2 => 'Toyota',
3 => 'Nissan');
$maker = $makes[$_POST['Make']];
You can achive this with creating new array:
<?php
$array = array(1 => "Toyota", 2 => "Nissan", 3 => "BMW");
if (isset ($_POST['search'])) {
$maker = mysql_real_escape_string($_POST['Make']);
echo $array[$maker];
}
?>
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
Change your select box options value:
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<option value="Any">--Any--</option>
<option value="Toyota">Toyota</option>
<option value="Nissan">Nissan</option>
</select>
You cann't get the text of selected option in php. it will give only the value of selected option.
EDITED:
<select id="cmbMake" name="Make" >
<option value="0">Select Manufacturer</option>
<option value="1_Any">--Any--</option>
<option value="2_Toyota">Toyota</option>
<option value="3_Nissan">Nissan</option>
</select>
ON php file:
$maker = mysql_real_escape_string($_POST['Make']);
$maker = explode("_",$maker);
echo $maker[1]; //give the Toyota
echo $maker[0]; //give the key 2
you can make a jQuery onChange event to get the text from the combobox when the user select one of them:
<script>
$( "select" )
.change(function () {
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
$('#EvaluationName').val(str);
})
.change();
</script>
When you select an option, it will save the text in an Input hidde
<input type="hidden" id="EvaluationName" name="EvaluationName" value="<?= $Evaluation ?>" />
After that, when you submit the form, just catch up the value of the input
$Evaluation = $_REQUEST['EvaluationName'];
Then you can do wathever you want with the text, for instance save it in a session variable and send it to other page. etc.
I agree with Ajeesh, but there are simpler ways to do this...
if ($maker == "2") { }
or
if ($maker == 2) { }
Why am I not returning a "Toyota" value? Because the "Toyota" choice in the Selection Box would have already returned "2", which, would indicate that the selected Manufacturer in the Selection Box would be Toyota.
How would the user know if the value is equal to the Toyota selection in the Selection Box? In between my example code's brackets, you would put $maker = "Toyota" then echo $maker, or create a new string, like so: $maketwo = "Toyota" then you can echo $makertwo (I much prefer creating a new string, rather than overwriting $maker's original value.)
If the user selects "Nissan", will the example code take care of that as well..? Yes, and no. While "Toyota" would return value "2", "Nissan" would instead return value "3". The current set value that the example code is looking for is "2", which means that if the user selects "Nissan", which represents value "3", then presses "Search", the example code would not be executed. You can easily change the code to check for value "3", or value "1", which represents "--Any--".
What if the user clicks "Search" while the Selection Box is set to "Select Manufacturer"? How can I prevent them from doing so? To prevent them from proceeding any further, change the set value of the example code to "0", and in between the brackets, you may place your code, then after that, add return;, which terminates all execution of any further code within the function / statement.

Categories