I have two dropdowns which values are populated from MySQL. The second dropdown values depends on the first dropdown option.
Anyways, the code is working. Now using my code I am posting hospital_id to another php. But I want to display hospital_name as text on the dropdown as well, but as of now I am only able to display the hospital_id.
Please see me code below and suggest me a solution:
$query = "SELECT bp_id,bp_name FROM mfb_billing";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$categories[] = array("bp_id" => $row['bp_id'], "val" => $row['bp_name']);
}
$query = "SELECT bp_id, hospital_id, hospital_name FROM mfb_hospital";
$result = $db->query($query);
while($row = $result->fetch_assoc()){
$subcats[$row['bp_id']][] = array("bp_id" => $row['bp_id'], "val" => $row['hospital_id']);
}
$jsonCats = json_encode($categories);
$jsonSubCats = json_encode($subcats);
This is the script:
<script type='text/javascript'>
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 1; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].bp_id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].hosp);
}
}
</script>
This is my form:
<body onload='loadCategories()'>
<form id="reportvalue" action="testpj2.php" method="post">
<select id='categoriesSelect'>
<option value="1">Select Billing Provider</option>
</select>
<select name='hospitalname[]' id='subcatsSelect' multiple='multiple'>
<option value="all">Select Billing Provider</option>
</select>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to">
<?php
//$a = $_REQUEST['hospitalname[]'];
//echo $a;
?>
<input type="submit" name="Submit" value="Submit">
</form>
HTML
<select id="someId"></select>
Javascript
document.getElementById('someId').innerHTML="
<option value='value1'>"+option1+"</option>
<option value='value2'>"+option2+"</option>
<option value='value3'>"+option3+"</option>";
Update:
for dynamic data from SQL query,
Try putting these codes after query execution. replace $row['value'] and $row['option'] with the respected dynamic values.
echo"<script type='text/javascript'> var str = '' </script>";
while($row = $result->fetch_assoc())
{
echo"<script type='text/javascript'>
str = str + '<option value='+".$row['value']."+'>'+".$row['option']."+'</option>
</script>";
}
echo"<script type='text/javascript'>
document.getElementById('someId').innerHTML = str
</script>";
if you are getting the hospital id then it is very easy to populate the selected value by getting it through from mysql
$query = "SELECT hospital_id, hospital_name FROM mfb_hospital where hospital_id = '$_post['hospital_id']'";
$result = $db->query($query);
$res = mysql_fetch_array($result)
In your select option value code put this code
<option value="your ids here will populate" <?php if($hospital_array['hospital_id']==$res['hospital_id']) echo "selected=selected" ?>>Your hospital name will display here which you selected</option>
Related
I have a running code that does sql query based on 1 <select> dropdown value. May I ask how will I be able to do multiple query parameters using 2 or more <select> dropdown?
Example. I sorted my data based on accounttitle now I want to sort accountttitle by YEAR(datedue), how will I do this?
This is what I got so far.
For isset()
if(isset($_GET['accounttitle'])){
$accounttitle = $_GET['accounttitle'];
$year = date('Y');
if(isset($_GET['year'])){
$year = $_GET['year'];
}
else "PLEASE SELECT OPTION";
}
?>
For <select>
<div class="col-sm-9">
<select class="form-control" id="select_account_title" style="text-transform:uppercase" required>
<option value="">PLEASE SELECT OPTION</option>
<?php while ($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)): ?>
<option value="<?= urlencode($row['accounttitle'])?>"><?= $row['accounttitle'] ?></option>
<?php endwhile; ?>
</select>
<label>Select Year: </label>
<select class="form-control input-sm" id="select_year">
<?php
for($i=2013; $i<=2033; $i++){
$selected = ($i==$year)?'selected':'';
echo "
<option value='".$i."' ".$selected.">".$i."</option>
";
}
?>
</select>
</div>
For SQL
$sql = "SELECT referenceno, employeeidno, accounttitle, 'ON PROGRESS' as debit, postedby, approvedby, notedby, credit FROM earningsamendment where accounttitle= '$accounttitle' and YEAR(datedue)='$year'";
$query = sqlsrv_query($conn, $sql, array(), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
while($row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC)){
This is my concern.
$(function(){
$('#select_account_title').change(function(){
window.location.href = 'earnings_amendment.php?accounttitle='+$(this).val();
});
});
</script>
How will I enable <script> to read 2 parameters? like
$(function(){
$('#select_account_title').change(function(){
window.location.href = 'earnings_amendment.php?accounttitle='+$(accounttitle).val()'&year='+$(year).val();
});
});
</script>
or something similar?
You need an on change with multiple selectors.
$(document).on('change', '#select_account_title, #select_year', function() {
var account_title = $("#select_account_title").val();
var year = $("#select_year").val();
window.location.href = 'earnings_amendment.php?accounttitle='+account_title+'&year='+year;
});
I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>
I have follow a web site to made a Dynamic Dependent Select using SQL JQuery Ajax with PHP , and it's work !, but i would like to get the value from the second and third select box once i chosen , and auto fill in to the other input box. is that possible to do it ?
look like this
if i selected all 3 select box and the data have shown (fetched from sql)
can i duplicate those 2 value to other input box and auto filled to the box???
Much thanks
code below
Index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center">Dynamic Dependent Select Box using JQuery Ajax with PHP</h2><br /><br />
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<br />
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<br />
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.action').change(function(){
if($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if(action == "country")
{
result = 'state';
}
else
{
result = 'city';
}
$.ajax({
url:"fetch.php",
method:"POST",
data:{action:action, query:query},
success:function(data){
$('#'+result).html(data);
}
})
}
});
});
</script>
fatch.php
<?php
if(isset($_POST["action"]))
{
$connect = mysqli_connect("localhost", "root", "", "testing");
$output = '';
if($_POST["action"] == "country")
{
$query = "SELECT state FROM country_state_city WHERE country = '".$_POST["query"]."' GROUP BY state";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select State</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
}
}
if($_POST["action"] == "state")
{
$query = "SELECT city FROM country_state_city WHERE state = '".$_POST["query"]."'";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select City</option>';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
}
}
echo $output;
}
?>
Create two input boxes and then use jquery to populate these on change of two select boxes like this.
<div>
<input id="forState" />
<input id="forCity" />
</div>
SCRIPT:
$('#state').change(function(){
console.log($("#state option:selected").val());
$('#forState').val($("#state option:selected").val());
} );
$('#city').change(function(){
console.log($("#city option:selected").val());
$('#forCity').val($("#city option:selected").val());
} );
I am trying to filter the value displayed in a select box, based on another value in input textbox in html modal form. I am getting the following error"Notice: Undefined index: gender in C:\xampp\htdocs\series\Register\indexentries1.php on line 3". If i test it and use a value like "Male" instead of "'".$_POST["gender"]."' then it does filter and display correctly in select box.
<?php
include("connection.php");
$query = "SELECT * FROM tblcategories WHERE gender = '".$_POST["gender"]."'";
$result = mysqli_query($connection, $query);
$output = '';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
}" error.
?>
In the html side i have
<input type="text" name="gender" placeholder="Gender" id="gender"/> that has a value ie "Male" already.
select box:
<label>Select Category</label>
<select name="category_id" id="category_id" class="form-control" >
<option value="">Select Category</option>
<?php echo $output; ?>
</select>
How can i filter this "$output value" based on "gender value" in input text box. Please assist this novice PHP programmer. thx
I also use
$(document).on("loaded.rs.jquery.bootgrid", function()
{
usersTable.find(".update").on("click", function(event)
{
var id = $(this).data("row-id");
$.ajax({
url:"fetch_single_entries.php",
method:"POST",
data:{id:id},
dataType:"json",
success:function(data)
{
$('#usersModal').modal('show');
$('#category_id').val(data.category_id);
$('#category_name').val(data.category_name);
$('#idno').val(data.idno);
$('#surname').val(data.surname);
$('#firstname').val(data.firstname);
$('#age').val(data.age);
$('#gender').val(data.gender);
$('.modal-title').text("Edit Entries");
$('#id').val(id);
$('#action').val("Edit");
$('#operation').val("Edit");
}
});
});
});
And this fetch form to populate the modal
<?php
//fetch_single.php
include("connection.php");
if(isset($_POST["id"]))
{
//$output = array();
$query = "SELECT * FROM tblentries WHERE id = '".$_POST["id"]."'";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_array($result))
{
$output["category_id"] = $row["category_id"];
$output["category_name"] = $row["category_name"];
$output["idno"] = $row["idno"];
$output["surname"] = $row["surname"];
$output["firstname"] = $row["firstname"];
$output["age"] = $row["age"];
$output["gender"] = $row["gender"];
}
echo json_encode($output);
}
?>
I removed some of the fields above
I have a sql table looks like this.
id name cname
1 Ash abc
2 Ash abc
3 Ashu abc
4 Ashu xyz
5 Yash xyzz
6 Ash xyyy
I want user to select a value from first select drop down list that shows DISTINCT name values and its working fine.
1st Select:
<select id="select1" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Category</option>
<?php
$resultd = mysqli_query($mysqli,"SELECT DISTINCT name FROM advertise");
if ($resultd)
{
while($tier = mysqli_fetch_array($resultd))
{
echo '<option value="' .$tier['name'] . '">' . $tier['name'] . '</option>';
}
}
?>
</select>
now i want to show values of second select drop down box based on first. Jquery i am using for this is :
<script>
$(function(){
var conditionalSelect = $("#select2"),
// Save possible options
options = conditionalSelect.children(".conditional").clone();
$("#select1").change(function(){
var value = $(this).val();
conditionalSelect.children(".conditional").remove();
options.clone().filter("."+value).appendTo(conditionalSelect);
}).trigger("change");
});
</script>
2nd Select Box
<select id="select2" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Location</option>
<option class="conditional name" value="">cname</option>
</select>
All i want to know is what php query should i need to use to get values in 2nd select box based on first. I tried a lot to find solutions but i didn't find any solution that gets its values from database...Thanks in advance...
You may not need a 2nd Query and all those complexities if you do things a little differently. This means, you could achieve your goal using one single Query. The Code below demonstrates how. Note: This Solution uses JQuery to make things simpler.
To test this; just copy and paste the Code AS IS into a new File and see if it works as you had expected.
CHEERS & GOOD-LUCK!!!
<?php
// USE YOUR CONNECTION DATA... PDO WOULD BE HIGHLY RECOMMENDED.
// INTENTIONALLY USING mysqli (NOT RECOMMENDED) TO MATCH YOUR ORIGINAL POST.
$conn = mysqli_connect("localhost", "root", 'root', "test");
if (mysqli_connect_errno()){
die("Failed to connect to MySQL: " . mysqli_connect_error());
}
$resourceID = mysqli_query($conn, "SELECT * FROM advertise");
$all = mysqli_fetch_all($resourceID, MYSQLI_ASSOC);
$uniques = [];
$options1 = "";
if( !empty($all) ){
foreach($all as $intKey=>$advertiseData) {
$key = $advertiseData['name'];
$cName = getCNameForName($all, $key);
if (!array_key_exists($key, $uniques)) {
$uniques[$key] = $advertiseData;
$options1 .= "<option value='{$key}' data-cname='{$cName}'>";
$options1 .= $key . "</option>";
}
}
}
function getCNameForName($all, $name){
$result = [];
foreach($all as $iKey=>$data){
if($data["name"] == $name){
$result[] = $data['cname'];
}
}
return $result ? implode(", ", array_unique($result)) : "";
}
?>
<html>
<body>
<div>
<select id="select1" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Category</option>
<?php echo $options1; ?>
</select>
<select id="select2" required="required" class="custom-select standard">
<option value="0" selected="selected">Choose Location</option>
</select>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
(function($) {
$(document).ready(function(){
var firstSelect = $("#select1");
var secondSelect = $("#select2");
firstSelect.on("change", function(){
var main = $(this);
var mainName = main.val();
var mainCName = main.children('option:selected').attr("data-cname");
var arrCName = mainCName.split(", ");
var options2 = "<option value='0' selected >Choose Location</option>";
for(var i in arrCName){
options2 += "<option value='" + arrCName[i] + "' ";
options2 += "data-name='" + mainName + "'>" + arrCName[i] + "</option>\n";
}
secondSelect.html(options2);
});
});
})(jQuery);
</script>
</body>
</html>