How can I Fetch data after selecting from dropdown list - php

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

Related

Populate dropdown based on checkbox

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
}
?>

How to get a value of a select input tag with options taken from a database using POST method?

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"doctor1\">" . $row['Title'].' '.$row['Name'].' '.$row['LastName'] . "</option>";
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>
Above is a form I created. I used POST method. This form has a select input tag and it's options are taken from my database. When form is submitted I need to access the value selected by user using $_POST['doctor'] function. But it doesn't give me any value. Can anyone help me?
If the ID for each entry in the "physician" table is stored in a column "PhysicianID", you should try the following code snippet:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<select name="doctor">
<?php
$con = mysqli_connect("---","---","---","---") or die("Can't Connect to the Database.");
$sql = mysqli_query($con, "SELECT PhysicianID, Title, Name, LastName FROM physician");
while ($row = $sql->fetch_assoc()){
echo '<option value="'.$row['PhysicianID'].'">'.$row['Title'].' '.$row['Name'].' '.$row['LastName'].'</option>';
}
?>
</select>
<input type='submit' value="Filter"><br>
</form>

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>

selected value from the listbox in php

I want the value which I select from the listbox and want to store in php variable because I want to use that variable for further use. Please help..
<form name="myform" method="post">
<?php
include('dbconnect.php');
db_connect();
$query = "SELECT * FROM test_customer"; //Write a query
$data = mysql_query($query); //Execute the query
?>
<select id="cust_name" name="mylist" onchange="selectedvalue()">
<?php
while($fetch_options = mysql_fetch_array($data)) { //Loop all the options retrieved from the query
?>
//Added Id for Options Element
<option id ="<?php echo $fetch_options['test_id']; ?>" value="<?php echo $fetch_options['cust_name']; ?>"><?php echo $fetch_options['cust_name']; ?></option><!--Echo out options-->
<?php
}
?>
</select>
</form>
<select id="cust_name" name="mylist" onchange="selectedvalue(this.value)">
access that values selectedvalue(val) in parameter
get that selected value and store it in input type= hidden as u need it for further use..
If you want to store into a php-variable, you must post the form. I've added a submit-button below. You also must speciy an action to where the form is submitted to: action="whatever.php"
<form name="myform" method="post" action="whatever.php"> <!-- added action here -->
<?php
include('dbconnect.php');
db_connect();
$query = "SELECT * FROM test_customer"; //Write a query
$data = mysql_query($query); //Execute the query
?>
<select id="cust_name" name="mylist" onchange="selectedvalue()">
<?php
while($fetch_options = mysql_fetch_array($data)) { //Loop all the options retrieved from the query
?>
//Added Id for Options Element
<option id ="<?php echo $fetch_options['test_id']; ?>" value="<?php echo $fetch_options['cust_name']; ?>"><?php echo $fetch_options['cust_name']; ?></option><!--Echo out options-->
<?php
}
?>
</select>
<!-- added submit button -->
<input type="submit" value="ok" />
</form>
Create a php-file called whatever.php and in this file, store the value into $cust_name by doing this:
<?php
$cust_name = $_POST['mylist']; //mylist is the name of the select-list
?>
If you want to post the form without having to reload the page, you must use something called ajax.
This works for me.Try this example.
public function getAptTypesBySelectedKy($valKy) {
$stmt = "SELECT ap_typ_ky, ap_typ_desc FROM apt_types WHERE ap_stat=1 order by ap_typ_desc";
try {
$con = DataHandler::connect();
$values = $con->prepare($stmt);
if ($values->execute()) {
echo '<select class="form-control" name="type" id="apt_types_slc">';
while ($row = $values->fetch(PDO::FETCH_ASSOC)) {
if ($valKy === $row['ap_typ_ky']) {
echo '<option value="' . $row['ap_typ_ky'] . '" selected>' . $row['ap_typ_desc'] . '</option>';
} else {
echo '<option value="' . $row['ap_typ_ky'] . '">' . $row['ap_typ_desc'] . '</option>';
}
}
echo '</select>';
}
} catch (PDOException $ex) {
echo 'Error on apartment types';
$error = $ex;
print_r('<pre>' . $ex->getCode() . '</pre>');
print_r('<pre>' . $ex->getMessage() . '</pre>');
}
}
In your html form page.
$__typKy = $_RA['typeky'] //this line get the selected value from database and set as parameter to the function getAptTypesBySelectedKy()
<?php
$__typKy;
if (isset($_RA)) {
$__typKy = $_RA['typeky'];// you need to find this key from database.
//this is the selected value key of `<select>`
}
$var = new DataHandler();
$var->getAptTypesBySelectedKy($__typKy);
?>

update existing row in mysql using php coding

in my db i have 20+ columns. i added 19 columns throught input form and stored in db succesfully. i fetch few rows from db in my main page. in my main page 1 more column is there. that is status column, it is a combo box type. if i click status column it should show 4 values. i want to select one of the values and then when i click save button it must go to stored in db with that same ID. how to do that? i tried but its not updated in mysql db...
mainpage combo box coding:
echo "\t<td><form action=statusdb.php method=post>
<select name=update><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select>
<input name=\"update[".$a_row['slno']."]\"; type=submit id=id value=Save></form>
</td>\n";
status db coding:
if (isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$sql = mysql_query("UPDATE guestdetails SET status = '" . $_POST['update'] ."'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
help me how to do that?
In your IF should be $_POST, not $_GET
Also, need to add WHERE clause, like this:
if (isset($_POST['id']))
{
$id = mysql_real_escape_string($_POST['id']);
$update= mysql_real_escape_string($_POST['update']);
$sql = mysql_query("UPDATE guestdetails SET status = '$update' WHERE id='$id'");
if(!$sql)
{
die("Error" .mysql_error());
}
}
Also, you used name update twice, once in <select> once in <input>, take that one from <input> out, make it hidden field with name id and value of your slno row:
echo "\t<td>
<form action=statusdb.php method=post>
<select name=update>
<option value=empty></option>
<option value=Confirm>Confirm</option>
<option value=Processing>Processing</option>
<option value=Pending>Pending</option>
<option value=Cancelled>Cancelled</option>
</select>
<input name='id' type='hidden' value='".$a_row['slno']."';>
<input type='submit'>Save</button>
</form>
</td>\n";
Try like below:
<form action="statusdb.php" method="post">
<?php
while($a_row = mysql_fetch_array($sql)) {
$sl_no = $a_row['slno'];
echo '<select name="update['.$sl_no.']"><option value=empty></option><option value=Confirm>Confirm</option><option value=Processing>Processing</option><option value=Pending>Pending</option><option value=Cancelled>Cancelled</option></select> ';
echo '<input type="hidden" name="sl_no[]" value="'.$sl_no.'" />';
}
?>
<input name="update_rows" type="submit" value="Save">
</form>
<?php
if(isset($_POST['update_rows'])) {
$nums = $_POST['sl_no'];
$update = $_POST['update'];
foreach($nums as $sl) {
$sl_no = $sl;
$val = $update[$sl_no];
$sql_update = mysql_query("UPDATE guestdetails SET status = '$val' WHERE sl_no='$sl_no'");
}
}
?>
you are not submitting any id to status db.

Categories