How can I pass an HTML value to a PHP variable - php

I have a simple web app made with CodeIgniter 3 and I have created a simple dropdown menu where the user can select from a variety of options from the database.
Here is the code:
<?php
$sql4 = "SELECT DISTINCT (color), id FROM porta_color ORDER BY color ASC ";
$result4 = $conn->query($sql4);
?>
<select id="color" class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="k_color" required >
<?php
if ($result4->num_rows > 0)
{
while($row4 = $result4->fetch_assoc())
{
if($row4['id']>0)
{?>
<option value="<?=$row4['id'];?>"><?=$row4['color'];?></option>
<?php }}}?>
</select>
Now what I want to do is based on the selection from the user to pass the value to a PHP variable.
Any idea how I might do that?

Wrap your select into form tags
and add submit or button element
<form>
<select id="color" class="form-control selectpicker" data-size="10" data-live-search="true" data-style="btn-white" name="k_color" required >
<option value="color1">Color 1</option>
<option value="color2">Color 2</option>
<option value="color3">Color 3</option>
</select>
<input type="submit" values="Choose color">
<button>Another way for submit form</button>
</form>
But true way is using framework abilities

Related

Set select input value unsing php echo

I have a select input for categories that set a list (category_id + category_value) from the database using the class categories_list. Now I want to set the value of selected category using get method when a user click on a specific category from another page. My get method is working fine, but the select input doesn't fetch the get variable with php echo.
I have tried to use instead jquery $("select[name='categories_id']").val(); but it works only if i add a clicked event that i don't want it .
<div class="control-group">
<label class="control-label alignL" for="categories_id">Catégories </label>
<select id="categories_id" class="form-control common_selector categories_list" name="categories_id" value" <?php if (isset($_GET["cat"])) { echo $categorytag; } ?>" >
</select>
</div>
Please consider the following example.
<div class="control-group">
<label class="control-label alignL" for="categories_id">Catégories </label>
<select id="categories_id" class="form-control common_selector categories_list" name="categories_id">
<option value="1001">Cat 1</option>
<option value="1002">Cat 2</option>
<option value="1003" selected>Cat 3</option>
<option value="1004">Cat 4</option>
<option value="1005">Cat 5</option>
</select>
</div>
The <select> element does not have a value attribute.
Attribute
Description
autofocus
Specifies that the drop-down list should automatically get focus when the page loads
disabled
Specifies that a drop-down list should be disabled
form
Defines which form the drop-down list belongs to
multiple
Specifies that multiple options can be selected at once
name
Defines a name for the drop-down list
required
Specifies that the user is required to select a value before submitting the form
size
Defines the number of visible options in a drop-down list
See More: https://www.w3schools.com/tags/tag_select.asp
You can get the value of the element when an <option> has been selected.
$(function() {
console.log("Current Value", $("#categories_id").val());
$("#categories_id").change(function() {
console.log("Selected", $(this).val());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="control-group">
<label class="control-label alignL" for="categories_id">Catégories </label>
<select id="categories_id" class="form-control common_selector categories_list" name="categories_id">
<option value="1001">Cat 1</option>
<option value="1002">Cat 2</option>
<option value="1003" selected>Cat 3</option>
<option value="1004">Cat 4</option>
<option value="1005">Cat 5</option>
</select>
</div>
You will want to adjust your PHP to build the Select element and Options properly before sending it to the browser. Then, if you are performing some action via JavaScript or jQuery, it will be done Client side.

How to display an alert message if the value is blank in the form

I have a form (bootstrap) in the script and need it if the user does not select the language and the value "" is blank to display the alert message and that he had to choose a language to proceed on the next step.
(as you can see the empty value in the form: value" " represent "Select Language")
I am using that form for google widget tool for translation, and when the visitor dont click anything and proceed to save file into the database , in the database I get value: "Select language" , I need that they pick one of the languages from the dropdown menu.
This is the form code:
<div class="form-group">
<label for="recipient-name" class="col-form-label">Language:</label>
<input type="text" class="form-control langinput" id="country" value="" readonly>
<select class="form-control langselect" aria-label="Language Translate Widget" id="country" style="display: none">
<option value="">Select Language</option>
<option value="English">English</option>
<option value="Afrikaans">Afrikaans</option>
<option value="Albanian">Albanian</option>
<option value="Amharic">Amharic</option>
<option value="Arabic">Arabic</option>
here is the button code for saving files into the database:
<button style="margin-top: -5%" background-color="#357ae8" type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal" data-whatever="#getbootstrap" onclick="lang1()">Save to Database</button>
lang1 Function:
var langPath = $("select.goog-te-combo option:selected").text();
/*document.getElementById("country").options[document.getElementById("country").selectedIndex].text = langPath;
document.getElementById("country").options[document.getElementById("country").selectedIndex].value = langPath;*/
document.getElementById("country").value = langPath;
//$(".langinput").value = langPath;
//$('input[type="text"][class="langinput"]').prop("value", "langPath");
//$('.langinput').text(langPath);
$('.langinput').attr('value', langPath);
//$(".langinput").display = "inline";
}
/*function stoppedTyping(){
if($('#subtitle').val().length > 1 && $('#country').val().length >0 ) {
document.getElementById('submit_button').disabled = false;
} else {
document.getElementById('submit_button').disabled = true;
}
}
function stoppedSelect(){
if($('#subtitle').val().length > 1 && $('#country').val().length >0 ) {
document.getElementById('submit_button').disabled = false;
} else {
document.getElementById('submit_button').disabled = true;
}
}*/
With bootstrap just add required to the select:
<select class="form-control langselect" aria-label="Language Translate Widget" id="country" style="display: none" required>
<option value="">Select Language</option>
<option value="English">English</option>
<option value="Afrikaans">Afrikaans</option>
<option value="Albanian">Albanian</option>
<option value="Amharic">Amharic</option>
<option value="Arabic">Arabic</option>
</select>
Edit
Change the buttons onclick to onsubmit:
<button style="margin-top: -5%" background-color="#357ae8" type="button" class="btn btn-success" data-toggle="modal" data-target="#exampleModal" data-whatever="#getbootstrap" onsubmit="lang1()">Save to Database</button>
Just recommending to rewrite this: <option value="">Select Language</option>
to this: <option selected disabled>Select Language</option>
When user clicks on the next button check if the select's value length is 0 and return it.

How to combine several dropdown list values in mysql query?

<form method="post" action="search.php">
<select name="Num[]">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op[]">
<option value="">Select One</option>
<option value=">4">>4</option>
<option value=">2">>2</option>
</select>
<br />
<select name="num2[]">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2[]">
<option value="">Select One</option>
<option value="<20000"><20000</option>
<option value="<40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</form>
Here is my code to provide a dropdown list for the user. It will act as a filter to generate more specific result through mysql and don't get the logic to combine these dropdown values.
I would like to have something like:
Select * from hotel where price < 40000;
and I will provide all keywords after "Where".
Select boxes name are defined as array in html and your requirement is a user can select a single option in a select box. So you need to update the name of select boxes. You no need to add < in select box values, These conditions used at server end. I have corrected the HTML.
<form method="post" action="">
<select name="Num">
<option value="">Select One</option>
<option value="numofpeople">Number of people</option>
</select>
<select name="op">
<option value="">Select One</option>
<option value="4">>4</option>
<option value="2">>2</option>
</select>
<br />
<select name="num2">
<option value="">Select One</option>
<option value="price">Price</option>
</select>
<select name="op2">
<option value="">Select One</option>
<option value="20000"><20000</option>
<option value="40000"><40000</option>
</select>
<br />
<div class="input-group-btn">
<button class="btn btn-default" type="submit" name="search_btn"><i class="glyphicon glyphicon-search"></i> Search</button>
</div>
</form>
Server Side code for handle selected values and add to query.
if(isset($_POST['search_btn'])){
$conditons = array();
if(isset($_POST['Num'])){
$conditons[] = '`people` = "'.$_POST['Num'].'"';
}
if(isset($_POST['op'])){
$conditons[] = '`option` < '.$_POST['op'];
}
if(isset($_POST['price'])){
$conditons[] = '`price` = '.$_POST['price'];
}
if(isset($_POST['op2'])){
$conditons[] = '`op2` < '.$_POST['op2'];
}
$conditons = implode(' & ', $conditons);
echo $query = 'select * from hotel where '.$conditons;
}
You an update your real field name in conditions. After added conditions, result query will be as -
select * from hotel where `people` = "numofpeople" & `option` < 4 & `op2` < 20000
Here is a very generic example that I just put together. This code is not tested, but I have written like this before.
<?php
// Checks to see if post variables are available
if(isset($_POST)) {
// Creates original command
$query = "SELECT * FROM hotel WHERE "
// gets each value from the post
foreach($_POST as $key => $value) {
$query .= $key . "=" . $value . "AND ";
}
// Removes the trailing "AND "
$query = substr($query, 0, -4);
echo $query;
}
If you need to switch things up depending on key, you can just do a switch inside of the foreach statement that will check the key value. The key is the "name" attr that is assigned in the HTML that you are posting from.
This method is also not sanitized because I did not get a response to which connection type you are using, but it shouldn't be that hard. If you need me to write it, then I would be more than happy to do so.

How do I use PHP to query my SQL database using SELECT tag in html

Basically I'd like to use the choices which the user has selected from a different select tags, and in essence store these as variables which I can then use to query my database in SQL.
My HTML code is here:
<div id ="search_elements">
<img src="UniSelect.jpeg">
<select>
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select>
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
</div>
And the type of php i would be looking to use would be:
//$con=mysqli_connect("localhost","adam","YjM3ZTYwOTQ5OWRmYWZh","adam_...");
//if (mysqli_connect_errno())
// {
// echo "Failed to connect to MySQL: " . mysqli_connect_error();
// }
// Perform queries
//$sql=mysqli_query($con,"SELECT CONTENT FROM Blog WHERE ID = 01");
//$result=mysqli_fetch_assoc($sql);
//echo $result['CONTENT'];
//mysqli_close($con);
To make it clear once more, I want to use the different values which the user selects, upon clicking a search button, have these query results shown in a table.
This solution a little differs from yours because you have no provided your form, submit button, etc. but in general, after a few changes, it should work too:
<form method="post" action="">
<img src="UniSelect.jpeg">
<select name="university">
<option selected disabled>Select a university</option>
<option value="ucl">UCL</option>
<option value="kings">Kings College</option>
<option value="imperial">Imperial College</option>
<option value="lse">London School of Economics</option>
</select>
<img src="PriceSelect.jpeg">
<select name="rent_price">
<option selected disabled>Select a weekly rent price</option>
<option value="50">0-£50</option>
<option value="100"> £100-£150</option>
<option value="150">£150-200</option>
<option value="200"> £200+</option>
</select>
<input type="submit" value="Submit form">
</form>
And now, to get values of these (something like this and I recommend to place it above your form):
if (!empty($_POST)) {
// Checking connection in here
$university_id = mysqli_real_escape_string($con, $_POST['university']);
$rent_price = mysqli_real_escape_string($con, $_POST['rent_price']);
$sql = mysqli_query($con, "SELECT * FROM university WHERE name = '".$university_id."'");
$result = mysqli_fetch_assoc($sql);
// Same thing goes for rent price
}

force option from <select> drop down before submit form

I want the user to be forced to select any option in the drop down apart from the default "selected" option
here is my drop down menu code;
<form><label>Select Tank:</label>
<select class="text2" name="tank" id="mySelect">
<option value="0" selected="selected">Select your tank</option>
<option value="4"> Tank#1 </option>
<option value="9"> Tank#2 </option>
<option value="21"> Tank#3 </option>
<option value="34"> Tank#4 </option>
</select>
<input type="button" id="btncheck" value="Submit"/>
</form>
and here is my java;
$('#btncheck').click(function(){
if ($("#mySelect ")[0].selectedIndex <= 0) {
alert("Please select a tank from the menu!");
return false;
}
});
jsfiddle: http://jsfiddle.net/36JZL/41/
for some reason it validates correctly but form isnt submitted.
You can do it with jQuery on client side but its not a good option to validate things on client side.
PasteBin: http://jsbin.com/zer/1
<form id="myForm">
<label>Select Tank:</label><br />
<select class="text" name="tank" id="tankSelector">
<option value="All" selected="selected"> Select Tank </option>
<?QUERY HERE TO PULL AND LOOP FROM DATABASE?>
<option value="<?php echo $row->id; ?>"> <?php echo $row->description; ?> </option>
<? END LOOP ?>
</select>
<input type="submit">
</form>
<script>
$(function() {
$('#myForm').submit(function(e){
if($('#tankSelector').val() == 'All') {
alert('Select tank!');
e.preventDefault();
}
});
});
</script>
<label>Select Tank:</label><br />
<select class="text" id="seltank" name="tank">
<option value="All" selected="selected"> Select Tank </option>
</select>
in the client side click event of your submit button add some javascript to check the value of your drop down.
if(document.getElementById("seltank").value == "All")
{
//put some code to alert the user or show error
return false; //this should prevent your post
}
Similar post is here How do I cancel form submission in submit button onclick event?
Here's what I do:
<select class="text2" name="tank" id="mySelect">
<option></option>
<option value="4"> Tank#1 </option>
<option value="9"> Tank#2 </option>
<option value="21"> Tank#3 </option>
<option value="34"> Tank#4 </option>
</select>
If the user hits submit without making a selection, they will be prompted to select an option automatically. The limitation is that you don't get a pretty little "select an option" placeholder.
Maybe this can help. Im yet to find a stable answer
If using php:
$val = $_POST['select_input']; <--- works fine
or
$val = $request->select_input <---- can be problematic
On Html
<select id="select_input" name="select_input" >
<option value="0">Pending</option>
<option value="1">Approved</option>
<option value="0" selected>Pending</option>
</select>

Categories