I'm working on a small website and I'm currently stuck on a small issue.
Ive got a set of dropdown boxes created and populated in HTML, for example:
<select name="heatingType" id="heatingType" required>
<option value="" disabled selected>Select Your Option</option>
<option value = "Gas">Gas</option>
<option value = "Electricity">Electricity</option>
<option value = "Other">Other</option>
</select>
I'm able to store the values in a variable once the form has been posted/submitted, These are stored in my Controller Class eg:
$newCalc = new ConCalc();
// instantiate drawing tool
$draw = new DrawTool();
// parse (render) appliance view
$renderedView = $draw->render('../View/calculator.php', array('calcvalues' => $newCalc->getValues()));
if(isset($_POST['btn-calcCon'])){
$heatType = $_POST['heatingType'];
$meterType = $_POST['meterType'];
$bedrooms = $_POST['noBedrooms'];
$house = $_POST['houseType'];
$age = $_POST['houseAge'];
echo $heatType;
echo $meterType;
echo $bedrooms;
echo $house;
echo $age;
}
echo $renderedView;
If i echo out any of the varibales then it will display the value that was selected and posted in that dropdown.
My table structure is as follows:
HeatingType MeterType Bedrooms HouseType HouseAge Consumption
Gas Standard 1 or 2 Flat Less than 11 years 5430
Gas Standard 1 or 2 Flat More than 11 years 7270
So for example, if i chose Gas, Standard, 1 or 2, Flat and Less than 11 then i should have 5430 returned.
Now the problem I'm facing is how to use these posted values in a select statement,
I know i need to do something along the lines of :
SELECT Consumption fron ConTable WHERE HeatingType LIKE heatingTypeDropdownValue AND MeterType LIKE MeterTypeDropDownValue etc etc.
but im not exactly sure
Any help will be appreciated
Thanks!
I solved it by creating a session array:
`$_SESSION['post-data'] = $_POST;
$_SESSION['post-data']['heatingType'];
$_SESSION['post-data']['meterType'];
$_SESSION['post-data']['noBedrooms'];
$_SESSION['post-data']['houseType'];
$_SESSION['post-data']['houseAge'];`
And then using $_SESSION['post-data']['heatingType'] In the where clause
Related
I have a form on my website where one can select multiple other editors for a post.
The list of qualified editors is echoed by PHP, which works. But when multiple are selected HTML makes it into one list of the ids. F.E. If Jay (id = 4) and Sam (id = 9) are selected. The received value will be $_POST['editors'] = 49.
My code:
<select multiple class="editors" name="editors" id="editors">
<?php
//Gebruikers ophalen
$editorArr = getEditors();
foreach($editorArr as $editor){
echo "<option value='".$editor['id']."'>".$editor['email'].' - '.$editor['type']."</option>";
}
?>
</select>
and the handling PHP
$editors = htmlentities($_POST['editors']);
Okay! Try this:
<select class="editors" name="editors[]" id="editors" multiple>
<?php
//Gebruikers ophalen
$editorArr = getEditors();
foreach ($editorArr as $editor) {
echo "<option value='".$editor['id']."'>".$editor['email'].' - '.$editor['type']."</option>";
}
?>
</select>
The name should be an array so it can treat all selected values separately.
Hope it helps
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.
}
Ok, so this one is a little confusing. I have select dropdowns that are produced by PHP. It can be 4 selects, or 30 select dropdowns. Then there's option values. Here's what I have so far
<?php while($row = mysql_fetch_assoc($notes)){ ?>
<select name="milestone" id="milestone[<?php echo $row['id']; ?>]">
<option value="Enrollment Date">Enrollment Date</option>
<option value="Discharge Date">Discharge Date</option>
<option value="A/C Start">A/C Start</option>
<option value="Completion Date">Completion Date</option>
</select>
<?php } ?>
If I have 4 select boxes, I might have arrays as follows: milestone[2134], milestone[2222], milestone[225], and milestone[1022]
The array number is the id of the mysql table entry I need to update with the value of that specific select dropdown. I was thinking maybe to use milestone[][id] and loop through that?
Any ideas since there might be 20 select dropdowns?
Thanks!
do you want to fetch the values of your options from the database as well as the id ? Then you should to mysql_fetch_array or mysql_fetch_object function instead of mysql_fetch_assoc. This function only returns the number of the results while the two above returns the number as well as values.
Got it!
First, I had to apply the array to the name of the select like so and set the id value:
<select name="milestone[]" class="mstones" id="<?php echo $row['session_id']; ?>">
Then, with jquery, looped through the class and created created an array with the value being something I can "explode" in php:
var milestoneVal = [];
$("select.mstones").each(function(i, selected){
milestoneVal[i] = this.getAttribute('id') + ':' + $(selected).val();
});
Then, simple PHP
foreach($_POST['milestone'] as $v){
$m=explode(':',$v);
//db insert
}
It was tricky, and I'm sure there's a cleaner solution, but it works for me! Sorry for the poor initial explanation, and hope this helps someone else.
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();
}
}
I've got a form like so:
Question: <input type="text" name="question[][text]" id="question" />
Type:
<select name="question[][type]" id="type">
<option value="1to5scale">1 to 5 scale</option>
<option value="freetext">Open text</option>
</select>
This gets repeated depending on how many items the user wants (cloned through jquery). And my php to action the form contains:
foreach ( $_POST['question'] as $key=>$question )
{
if ($key >= 1) {
$question_text = $question['text'];
$type = $question['type'];
$query = " INSERT INTO questions (question_text, survey_id, type) ".
" VALUES ('$question_text','$survey_id', '$type')";
mysql_query($query) or die('Error ,query failed');
}
}
Each question has a text item and a type item. However in the DB it's adding one row per question item (if that makes sense...), rather than one row per complete question. Any ideas where I'm going wrong, it's quite hard to debug forms I'm finding...
Change the form element name from question[][type] to question[type][]. What this form does is add to the question array for each form element ([] means add a new array element).
As the comment implies, make sure you sanitize the input.