Setting a select list from values in a database - php

I have 2 select lists, one naming products and another for quantities.
<select name="fish" id="fish">
<option value="blueFish">Blue Fish</option>
<option value="redFish">Red Fish</option>
<option value="pinkFish">Pink Fish</option>
<option value="greenFish">Green Fish</option>
</select>
<select name="numFish" id="numFish">
<option value="0">0</option>
<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>
<option value="6">6</option>
</select>
I would like it so when a product is chosen, the corresponding quantity from the database will be set accordingly.
So if there was a record that customer Billy had bought 5 Pink Fish, when I select Pink Fish, the quantity select list will change to 5.
This would be for use in a PHP form using a MySQL database.
Is such functionality possible, and if so how would I go about doing it?

You might want to google for ajax requests. What it does is detecting a change (in your case) through javascript, send the value you selected to another php script which should do a sql query to return the quantity. The ajax request will catch the returned value and through javascript again change the value from the select dropdown.
All this would happen in the background and your site wouldn't refresh.
If you are not very used to javascript you can have a look at the jquery framework, which makes this task a bit easier, and with a lot of examples documented.
I didn't paste any code because assume you are not familiar with javascript/jquery/ajax. You might want to read a bit of documentation and play around a bit, and come back when you have a concrete problem, that would be the normal workflow here in Stackoverflow.
Edit: (some code as requested by OP)
Javascript:
$('#fish').change(function(){
var fishType = $('#fish select option:selected');
$.ajax("getQuantity.php", {fish: fishType}, function(data){
data = JSON.parse(data);
if(data.status == "OK"){
var quantity = data.quantity;
$('#numFish option[value='+quantity+']').prop("selected", true);
} else {
alert("error");// or console.log(), whatever you prefer
}
}
});
php (getQuantity.php):
<?php
$fish = $_POST['fish']; //getting the fish type
$sql = "your SQL to select the fish quantity for that type";
$result = mysqli_query($mysqli, $sql);
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_assoc($result);
$data = array("status" => "OK", "quantity" => $row['quantity']); // you can just output a string with the number if you want, but this way you have more control and better debugging.
echo json_encode($data);
}
?>
It's a basic code, it still would need to catch some errors for the database or return a different status. But basically that's it. I didn't even test that code so use it as a guideline only.

Change <select name="fish" id="fish"> to <select name="fish" id="fish" onchange="getQuantity(this.value);">
Declare the following function in javascript:
function getQuantity( o ) {
// get the quantity from the database using ajax,
// and set the quantity dropdown here.
}

Related

HTML Dropdown menu with autosuggestion and auto updation

I am trying to develop a webpage based on html, css. I am using PHP for server side scripting.
I want a dropdown menu to be displayed with available options, But at the same time I need this drop down list to accept text. so I can choose from dropdown list as well from the text box whatever I want.
I found one solution for the above scenario and working fine, but what extra I want that, once I write something in the text box, which is not an options of the dropdown, from the next time it will auto include it.
e.g. ->
currently my dropdown is having say three options "Samsung", "Sony", "Apple"
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
Now, "Lenevo" is not available. For the First time in the text box I will write "Lenevo" as my choice, there after it will include it into the dropdown menu.
<option value="one">Samsung</option>
<option value="two">Sony</option>
<option value="three">Apple</option>
<option value="four">Lenevo</option>
.
.
Like that it will happen.
Thanks for help.. :)
The best solution would be something like select2. (JavaScript)
For examples look here: Link
If you want to stay with PHP only, you need to offer a from to submit text values:
(Disclaimer: This solution is quite bad practice. But it's an example on how to solve it, on a low level.)
1) offer a form
<input type="text" name="addSelection">
2) Read post request
$newOption = $_POST["addSelection"];
3) Persist new option somewhere (here Session, also possible are databases)
$_SESSION["additionalOptions"][] = $newOption;
4) Merge with standard options
$options = ["apple","banana"];
$options = array_merge($options,$_SESSION["additionalOptions"]);
5) Create Options in HTML
<select name="fruits">
<?php
foreach($options as $option){
echo '<option value="'+$option+'">'+$option+'</option>';
}
?>
</select>
Use select2 plugin
https://github.com/select2/select2
<script type="text/javascript" src="/assets/profile/js/select2.min.fda43621.js"></script>
var validateTag = function (term, data) {
var value = term.term;
var re = /^[a-z\d\-_\s]+$/i;
if (re.test(value))) {
return {
id: value,
text: value
};
}
return 'wrong_characters';
};
$("#selectAlt").select2({tags: true, maximumSelectionLength: 6, maximumInputLength: 20, createTag: validateTag});
HTML:
<select name="selectAlt[]" id="selectAlt" multiple="multiple" custom-placeholder="Genre">
<option value="Blues">Blues</option>
<option value="Classic Rock">Classic Rock</option>
<option value="Country">Country</option>
</select>

PHP Multiple Hidden Values Select Option

Is it possible to assign multiple values to select option drop down lists? I need to retrieve multiple pieces of data from each drop down when they are selected and I have only been able to get the "name" and an "id". The name is displayed for the user to select however it is the ID that is passed to be processed. Here is my code:
<?php
$att_1 = $att_1;
mysql_connect("xx.xx.xx.xx","xxxxxx","xxxxxx");
mysql_select_db("dezanjow_cf");
$sql=mysql_query("select id, name from model");
if(mysql_num_rows($sql)){
$select= '<select name="model">';
$select.='<option value="default">Select Model</option>';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['id'].'">'.$rs['name'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
This produces html that looks like:
<select name="model">
<option value="default">Select Model</option>
<option value="5">GH20</option>
<option value="6">GH21</option>
<option value="7">GH22</option>
</select>
I wish to display them like this (as example):
<select name="model">
<option value="default">Select Model</option>
<option value="5","abc">GH20</option>
<option value="6","def">GH21</option>
<option value="7","ghi">GH22</option>
</select>
Thus when the data is passed onto the next php script, I can use both data "5" and "abc" when the user selects "GH20". I have not seen much on Google about this and don't even know if this is possible. Please let me know if I am asking for the impossible! Many Thanks, Nick
Hey you cannot have multiple values like that because post or get will return just first value which in this case is 5
<option value="5","abc">GH20</option>
but you can make your value looks like this
<option value="5,abc">GH20</option>
and then in php script you can separate values by using explode function
explode(',', $_POST['model'])
which will return array that you can use
array( 0=> 5, 1=>abc)
Its better if you serialize your data then at next php script unserialize it.
$data=array($rs['id'], "abc"); //data to be stored
$serialized_data=serialize($data); //serialize data
$select.='<option value="'.$serialized_data.'">'.$rs['name'].'</option>';
IMPORTANT
//unserialize information
$unserialized_data=unserialize($serialized_data);
this will output the same array array('SOMEID', "abc")

Error while getting select box value with php

I am currently working on a project where a user chooses an option from a select box and submits a form, the form is then processed by PHP, and the PHP code determines what the select box value is, and does something based on that value.
My select box is called combined_group and has two select values: philharmonic_orchestra and symphony_orchestra.
This is how I am checking the selected value:
if($_POST['combined_group'] == "philharmonic_orchestra"){
$_SESSION['semesterprice'] = "170";
$_SESSION['fullprice'] = "330";
}
if($_POST['combined_group'] == "symphony_orchestra"){
$_SESSION['semesterprice'] = "275";
$_SESSION['fullprice'] = "530";
}
But when PHP runs through this code, neither if statement is chosen. I know that the value of $_POST['combined_group'] is, in fact, either of those two values, just PHP isn't picking it up for some reason.
Anybody care to help?
EDIT: My HTML form code is as follows
<select name="combined_group" class="OBJ-1">
<option value="" selected="">Select One</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra ">Symphony Orchestra</option>
</select>
Client side
<select name="combined_group">
<option value="">Select an option</option>
<option value="philharmonic_orchestra">Philharmonic Orchestra</option>
<option value="symphony_orchestra">Symphony Orchestra</option>
</select>
Server side
if (! isset($_POST["combined_group"]))
{
exit('not set');
}
if (trim($_POST["combined_group"]) == '')
{
exit('not selected');
}
if (trim($_POST["combined_group"]) == 'philharmonic_orchestra')
{
//business logic for 'philharmonic_orchestra'
}
else
{
//business logic for 'symphony_orchestra'
}
Most likely is a bad HTML syntax. Check if your option item has value attribute:
<option value="...">...</option>
The reason why your conditional statement is failing, is because of a space in your option's value.
<option value="symphony_orchestra ">
^ right there
What you will need to do is remove it:
<option value="symphony_orchestra">
^ deleted space
Technical sidenote:
Had your conditional statement been:
if($_POST['combined_group'] == "symphony_orchestra ")
^ notice the space
with the space before the quote, it would have worked.
Anything between quotes is considered and part of an element's value.

How to read a value from a select box with php?

im using the cms contao and i got an overview page of some projects with 3 filters, one of them looks like this:
<select name="catitem_region_de" id="ctrl_filter_field_catitem_region_de" class="select" onchange="window.location=this.options[this.selectedIndex].value">
<option value="../cartitem_country/Deutschland" selected="selected">– Region –</option>
<option value="../cartitem_partner_country/Deutschland/catitem_region_de/Europa">Europa</option>
<option value="../cartitem_partner_country/Deutschland/catitem_region_de/Amerika">Amerika</option>
</select>
As you can see, when u select an option, the page refreshes with the selected filter.
My problem is, i want on every visit / refresh of the page, that a php script reads the value of the selected="selected" option. So that it looks like this:
If the option is "-Regio-", display content for region and if the content is anything else, display another content.
How can i do this with php?
thx
If I were you, I would split your page in smaller pieces.
First part - Array of your links in JavaScript :
var links = { 0 : '',
1 : '../cartitem_partner_country/Deutschland/catitem_region_de/Europa',
2 : '../cartitem_partner_country/Deutschland/catitem_region_de/Amerika' };
Second Part - Drop Down box:
<select name="catitem_region_de" id="ctrl_filter_field_catitem_region_de" class="select" onchange="changeDDB()">
<option value="0" selected="selected">– Region –</option>
<option value="1">Europa</option>
<option value="2">Amerika</option>
</select>
Third Part - On Change JavaScript :
function changeDDB() {
var idx = document.getElementById("ctrl_filter_field_catitem_region_de").selectedIndex;
if(idx != 0) {
window.location = links[idx];
}
}

mysql update query with form array

Multiple posts but I'm still stuck...I'm missing something fundamental here. I have a form with a select:
<select name="camera_status[]">
<option <?php echo $enabled_option; ?>>Enabled</option>
<option <?php echo $disabled_option; ?>>Disabled</option>
</select>
This form is built with a loop to give a list of all camera settings. So you would have multiple cameras and their corresponding camera_status. Also I have a hidden input field with the camera_id:
The camera_id is processed with some javascript. Then I process that with:
$camera_id = $_POST['camera_id'];
if (is_array($_POST['camera_status']))
{
foreach ($_POST['camera_status'] as $camera_status) {
$query_status = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_status);
$db->query();
}
}
If I echo the camera_id it is correct. But my foreach runs an update query for the full list of cameras instead of just the one selected. So it updates only the last camera in the list. Let me know if it makes sense to update the full code. Obviously I'm going about this all wrong...
EDIT: Well if you have single selection then it is simpler than that:
HTML:
<select name="camera_status">
<option value="Enabled">Enabled</option>
<option value="Disabled">Disabled</option>
</select>
And PHP:
$camera_id = (int) $_POST['camera_id']; //Here you had SQL injection.
$camera_status = mysql_real_escape_string($_POST['camera_status']); //Neither that was protected.
$query_status = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_status);
$db->query();
You have a fundamental flaw in your thought process for the page. When you output more than one <select name="camera_status[]"> elements, you're going to get that many results back. With two of them, you'll get two values in the array, and so on.
What it sounds like you're doing is outputting a list of cameras, having the user select a camera to modify, and then, from then on, all of the camera settings now only apply to that one specific camera. If this is the case, then you don't need to use arrays for the camera settings, including camera_status. Just remove the array portion and stop outputting more than one HTML element for each camera setting (since you know that once a camera is selected, those values apply to that specific camera).
However, if your page that displays the multiple cameras allows the user to modify every camera and its settings, you'll need to accommodate for the user's input.
If the latter is the case, here's a neat trick - Modify your <select> so it looks like this when you're outputting your camera form:
<select name="camera_status[<?php echo $row['camera_id']; ?>]">
<option value="1">Enabled</option>
<option value="0">Disabled</option>
</select>
Now, when you grab $_POST['camera_status'], it'll be an array with the camera IDs as the keys and their selected value as the value. So now, you can do this:
if( is_array($_POST['camera_status']))
{
foreach ($_POST['camera_status'] as $camera_id => $camera_status) {
$camera_status = intval( $camera_status); // Be wary of SQL injection
$camera_id = intval( $camera_id);
$query_status = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_status);
$db->query();
}
}
Now this will update every camera with the correct value chosen.
Easy enough. Add value attributes to the <option> tags so that each of them will have a value
<select name="camera_status">
<option value="1" <?php echo $enabled_option; ?>>Enabled</option>
<option value="0" <?php echo $disabled_option; ?>>Disabled</option>
</select>
Then, in your php, look for that value
foreach ($_POST['camera_status'] as $camera_status) {
if($camera_status == 1) {
$query_status = 'UPDATE `#__cameras` SET `camera_status` ="'.$camera_status.'" WHERE `camera_id`='.$camera_id;
$db->setQuery($query_status);
$db->query();
}
}

Categories