Populate dropdown based on checkbox - php

I have a form that contains a checkbox and a dropdown list. I use PHP to populate the dropdown list from two MySQL tables. Which table I use depends on whether the checkbox was checked or not. But, as you can see from my code sample, I can only populate that dropdown list after I submit the form. I want to be able to keep clicking on the checkbox and keep re-populating the dropdown list without having to submit the form. I am still new to this, so, please, give me as simple a solution as possible.
PS. I have a small bug in the code that doesn't keep the checkbox checked/unchecked after I submit the form. Working on fixing it.
Thank you
<?php
$Prc_Earn = 'Prc';
if (isset($_POST['submitBtn']))
{
if (isset($_POST['chkbox']))
{
$sql = 'select distinct Symbol from price_history.quarterly_earnings_history';
$Prc_Earn = 'Earn';
}
else
{
$sql = 'select distinct Symbol from price_history.stock_symbol_list';
$Prc_Earn = 'Prc';
}
}
// Connect to the database
include ('../Connections/mysql_connect.php');
if ($dbcon)
{
?>
<form method='post'>
<label for=''>Earnings / Prices</label>
<input type='checkbox' name='chkbox' id='chkbox' <?php if ($Prc_Earn == 'Prc') { echo "checked"; };?>><br><br>
<label for='symbol'>Stock Symbol:</label>
<select name = 'symbol' id='symbol'>
<?php
$result = mysqli_query($dbcon, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{ echo '<option value="' . $row['Symbol'] . '">' . $row['Symbol'] . '</option>'; }
}
?>
</select><br><br>
<button class='button' type='submit' name='submitBtn' id='submitBtn'>View Data</button><br><br>
</form>
<?php
}
?>

Related

PHP selection of drop down menu not storing in variable

I have a simple table with staff names stored in the column f_operator_name.
I have a drop down menu in a php form with these staff names available for selection. Here is a snippet of the relevant the code:
<?php
echo "<h2>Operator: <select name=f_operator_id></h2>";
$sql="SELECT * FROM radio_archive_index_gui.t_operator ORDER BY f_operator_id";
$result = pg_query($connection, $sql);
if (!$result){
die("Error in SQL query: " . pg_last_error());
}
while ($arr = pg_fetch_array($result, null, PGSQL_ASSOC)){
$operator_id=$arr['f_operator_id'];
$operator=$arr['f_operator_name'];
echo "<option value='$operator'>$operator</option>";
}
echo "</select>";
##### submit form to carry out echo statement for testing purposes
echo "<ul>
<th><input type='submit' name='new' value='Confirm Information'/></th>
</form>
</ul>";
if (isset($_POST['new']))
{
echo $_POST['operator'];
}
?>
When someone selects the staff name I want it to be stored in a variable. I'm testing the submit form at the bottom which is intended to print out the name that has been selected ( in the variable operator), but it's not printing anything out. Can anyone see any issues?
EDIT *** Here's the updated code after some advice from Barmar with the variable information also, for some reason the echo statement still isn't working:
<?php
$connection = pg_connect("host=10.100.51.42 port=5432 dbname=reportingdb user=rai_gui password=password");
echo "<h2>Operator:</h2> <select name='f_operator_id'>";
$sql="SELECT * FROM radio_archive_index_gui.t_operator ORDER BY f_operator_id";
$result = pg_query($connection, $sql);
if (!$result){
die("Error in SQL query: " . pg_last_error());
}
while ($arr = pg_fetch_array($result, null, PGSQL_ASSOC)){
$operator_id=$arr['f_operator_id'];
$operator=$arr['f_operator_name'];
echo "<option value='$operator'>$operator</option>";
}
echo "</select>";
##### submit form to carry out echo statement for testing purposes
echo "<ul>
<th><input type='submit' name='new' value='Confirm Information'/></th>
</form>
</ul>";
if (isset($_POST['new']))
{
echo $_POST['f_operator_id'];
}
?>
You can't put <select> inside <h2> and then put the <option>s and </select> outside it. HTML elements have to be nested properly, and <option> has to be inside <select>.
Change it to:
echo "<h2>Operator:</h2> <select name='f_operator_id'>";
And the index in $_POST has to match the name of the <select>, so $_POST['operator'] should be $_POST['f_operator_id'].

Add input field based on drop down list using php variables

I'm in the middle of making a simple inventory system for keeping track of equipment going in and out of our doors. The inventory is stored in MYSQL, with a table looking like this: id name storage used location_storage location
This is all fun and games when I create a simple form with PHP, so it stays dynamic with the content from the server. I can update all values with no problem.
But for the sake of simplicity I'm looking into having a drop down menu, with a button, that creates/shows input fields in a form. The reason being is that I will have many rows in my table in the upcoming time. As the forms earlier have been made from server information, I will also need the scripts to be dynamic. Right now I'm stuck thinking about what I should do.
As of now, my code for the bits look like this:
"Static" PHP form:
<form action="<?php $_PHP_SELF ?>" method="POST">
<?php
//conn stuff
$sql = "SELECT id, name, storage, used, location FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo ' ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" />';
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
Check in PHP (check out is identical except for change of + and minus):
if(isset($_POST['sjekkinn'])){
//conn stuff
mysql_select_db( 'experimental' );
$newamount = $_POST['newamount'];
foreach($newamount as $key => $value){
$sql = "UPDATE inventory ". "SET storage = (storage + $value), used = (used - $value)". "WHERE ID = $key " ;
if (empty($value)) continue;
$retval = mysql_query( $sql, $conn );}
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully!<br>";
header("Refresh:1");
mysql_close($conn);
}
Those are all working great, but I would like to use something like the code below for a neater setup... Anyone got any advice?
Drop down list generated from MYSQL:
<form action="#" method="post">
<select name="selectinventory">
<?php
//conn stuff
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Add line">
</form>
Okay, so I found my own solution.
I ended up using my table-populated drop down list as I showed you in the last code box of the question. What came to my mind was that I could simply use the jQuery show/hide function.
What I did was to make a script that told (in "readable") div 'x' to show and move when option 'x' was selected and button clicked. I will show you my complete code in the end.
That way I could have my input fields each created inside a div from my table (the same that populated the drop down list), so I could manage them easier (probably possible to do it easier - but if it ain't broken, don't fix it). These were created outside the form. When I then click the previously mentioned button, the div will move inside the form. The next one I select will end up UNDER the previous one, instead of just showing up in table-order.
Feel free to shout any questions!
Here's the complete code:
<form action="<?php $_PHP_SELF ?>" method="post">
<select name="selectinventory" id="selectinventory">
<option selected="selected">Choose one</option>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}?>
</select>
<div id="btn">Add line</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$("#" + $("#selectinventory").val()).show();
$("#" + $("#selectinventory").val()).appendTo($(".selecteditems"));
});
});
</script>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div style="display:none" id="' . $row["id"]. '"> ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" /><br></div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
<form action="<?php $_PHP_SELF ?>" method="POST" name="isthisthearrayname">
<div class="selecteditems">
</div>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>

How can I Fetch data after selecting from dropdown list

I want to fetch data from dropdown list. Like if I choose employee id 40 from the dropdown list it will fetch the data from database of that employee and will shown in the textboxes.
this is my dropdown code. please help me how can i get the selected value.
<?php
$con=mysqli_connect("localhost","root","","hct_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php
$result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" . $row['employee_id'] . "</option>";
?>
</select>
First of all give some id to you select option like this:
<select class="form-control" name="employee_id" id='employee'>
Add you textbox like this:
<input type='text' name='emp_name' id='emp_name' />
Than use jquery and ajax something like this:
$('#employee').change(function(){
var selected_id = $(this).val();
var data = {id:selected_id};
$.post('getemp_name.php',data,function(data){
$('#emp_name').val(data);
});
});
getemp_name.php
if(isset($_POST['id'])){
//fire query using this id and get the name of employee and echo it
echo $emp_name;
}
<?php
if(isset($_REQUEST['submit']))
{
$value=$_POST['employee_id'];
$query = mysql_query($con,"SELECT employee_name FROM employee where employee_id=$value");
$result=mysql_fetch_array($query);
$emp_name=$result['employee_name'];
}
?>
<form action="" method="post" name="form">
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php $result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" .$row['employee_id'] . "</option>";
?>
</select>
<input type="submit" name="submit" value="submit">
</form>
<input type="text" value="<?=$emp_name?>" name="emp_name"/>
check this code as your need
To get your selected value, you have to reach the $_GET or $_POST supertables after the user submits the form.
So, after the submit, get it as, if you POST:
<?php
$employee_id = $_POST['employee_id']; ?>
If you GET:
<?php
$employee_id = $_GET['employee_id']; ?>
apply below function on onChange
function myFunction(mySelect) {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
example
That depends on what you want. If you want to use the selected ID in your query AFTER DOING A POST, you can use the following query:
"SELECT *
FROM `employee`
WHERE `employee`.`employee_id` = " . (int) $_POST['employee_id'] . "
LIMIT 1"
Assuming you are using the post method in your form.
You can easily learn how to fetch data from dropdown using this example by clicking Here This repository contains all the codes

displaying results based on combobox selection

I have a dynamic combobox and I have my Fetch button. When a user selects a value from combobox and clicks fetch button, all the other related values are displayed in a textbox for the user to edit and update records. And that works fine.
<form id="form1" method="post" action="edit.php">
<select name="ID" id="select">
<?php display_Id();?>
</select>
<input type="submit" name="Fetch" id="Fetch" value="Fetch" />
</form>
function display_Id() {
$query = "SELECT * FROM Flight";
$result = mysql_query($query) or die("Failed to fetch records");
confirm_query($result);
while($rows = mysql_fetch_array($result)) {
$flightNum = $rows['FlightNo'];
echo "<option value=\"$flightNum\" ";
echo " selected";
echo "> $flightNum </option>";
}
}
The problem is in the Fetch button. When user clicks Fetch, other values are displaying but the selected value from combobox is refreshing. How to make the values remain selected even after pressing the Fetch button?
Your question is incomplete in the sense, that you don't have your dislay_Id() code shown here. However, Generally speaking, you should add selected after <option value="something" programmatically,
Code should be something like this:
function displayId(){
if($value[x]== $currentValue) {
echo "<option value='$value[x]' selected>sth</option>";
}
else
{
echo "<option value='$value[x]'>sth</option>";
}
}
EDIT:: Your code adds a "selected" to each of the values, you must only add a "selected" to a current value.
So, your code must look like this:
echo "<option value=\"$flightNum\" ";
if($_POST['ID'] == $flightNum)
{
echo " selected";
}
echo "> $flightNum </option>";
while($rows = mysql_fetch_array($result))
{
$flightNum = $rows['FlightNo'];
echo "<option value=\"$flightNum\" ";
if($_POST['ID'] == $flightNum)
{
echo " selected";
}
echo "> $flightNum </option>";
}

HTML/PHP Survey not passing to MySQL database properly

I'm trying to make a small survey that populates the selections for the dropdown menu from a list of names from a database. The survey does this properly. I want to submit the quote the user submits with this name into a quote database. The quote text they enter into the field goes in properly, however, the name selected from the menu does not get passed in. Instead I get a blank name field.
I understand some of my code is out of context, but the name is the only thing that does not get passed in properly.
On form submit, I include the php file that submits this data to the database:
<form action="<?php $name = $_POST['name']; include "formsubmit.php";?>" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<input type="submit" value="Submit!" />
</form>
The variable $name comes from this (which populates my dropdown menu):
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
echo "</select>";
And here is my formsubmit.php:
<?php:
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
header("Location: quotes.php");
if (#mysql_query($sql)) {
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
Your form action stuff looks weird, but regardless, I think the problem you're having has to do with not setting $name = $_POST['name'] like you're doing with $quotetext = $_POST['quotetext']. Do that before the sql statement and it should be good to go.
edit to try to help you further, I'll include what the overall structure of your code should be, and you should tweak it to fit your actual code (whatever you're leaving out, such as setting $query for your name options):
file 1:
<form action="formsubmit.php" method="post">
<label> <br />What did they say?: <br />
<textarea name="quotetext" rows="10" cols="26"></textarea></label>
<select name='name'>
<?php
while ($temp = mysql_fetch_assoc($query)) {
echo "<option>".htmlspecialchars($temp['name'])."</option>";
}
?>
</select>
<input type="submit" value="Submit!" />
</form>
formsubmit.php:
<?php
mysql_select_db('quotes');
if (isset($_POST['quotetext'])) {
$quotetext = $_POST['quotetext'];
$name = $_POST['name'];
$ident = 'yankees';
$sql = "INSERT INTO quote SET
quotetext='$quotetext',
nametext='$name',
ident='$ident',
quotedate=CURDATE()";
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}
}
?>
echo "<select name='name'>";
while ($temp = mysql_fetch_assoc($query)) {
$nyme = htmlspecialchars($temp['name']);
echo "<option value='$nyme'>$nyme</option>";
}
echo "</select>";-
This way you will receive the value of the name in $_POST array
and you have to get that value out of $_POST array as well you need to change the
code add the following line to get the name in your script.
$name = $_POST['name'];
you need to change the form action tag
<form action='formsubmit.php' .....>
and in that file after successful insertion you can redirect the user to whereever.php.
so it was fun explaining you every thing bit by bit change this now in your code as well.
if (#mysql_query($sql)) {
header("Location: quotes.php");
} else {
echo '<p> Error adding quote: ' .
mysql_error() . '</p>';
}

Categories