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>
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 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>
I am using dropdown to select values, and after I click the submit button, my values change. Please help me retain the selected values. Using POST method I have got the solution, but I want to use with GET method. Is it possible?
1.) 1st select stmt:
<form action="" method="GET">
<select name="sort" >
<option value="inc_patientName">Patient Name</option>
<option value="inc_date">Date</option>
<option value="inc_status">Status</option>
<option value="inc_patientAge">Age</option>
</select>
<input type="submit" name="GETREPORT" value="Get Report"/>
if ($_GET)
{echo"hi";}
</form>
2.) 2nd select with while
<?php
//Selecting ward from table ward master
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
echo "<select name='ward'>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['ward_id'] . "'>" . $row['ward_name'] . "</option>";
}
echo "</select>";
?>
3.) 3rd select with javascript:
<select name="daydropdown" id="daydropdown" ></select>
<select name="monthdropdown" id="monthdropdown"></select>
<select name="yeardropdown" id="yeardropdown"></select>
<script type="text/javascript">
populatedropdown("daydropdown", "monthdropdown", "yeardropdown")
Javascript code:
<script type="text/javascript">
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield)
{
var today=new Date()
var dayfield=document.getElementById(dayfield)
var monthfield=document.getElementById(monthfield)
var yearfield=document.getElementById(yearfield)
for (var i=1; i<=31; i++)
dayfield.options[i]=new Option(i, i)
dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day
for (var m=0; m<12; m++)
monthfield.options[m]=new Option(monthtext[m], monthtext[m])
monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
var thisyear=1999
for (var y=0; y<45; y++){
yearfield.options[y]=new Option(thisyear, thisyear)
thisyear+=1
}
yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}
</script>
try
if(isset($_GET['sort'])) {
echo $_GET['sort'];
}
and get selected index
<option value="inc_patientName" <?php if (isset($_GET['sort']) && $_GET['sort'] == "inc_patientName") echo 'selected="seleceted"'; ?>>Patient Name</option>
and so on for all options values match
For 2nd dropdown:-
while ($row = mysql_fetch_array($result)) {?>
<option value="<?php echo $row['ward_id'];?>" <?php if (isset($_GET['sort']) && $_GET['sort'] == $row['ward_id']) echo 'selected="seleceted"'; ?>><?php echo $row['ward_name'];?></option>
<?php }
use it like this... it myt work.
<select name="ward">
<?php
$sql = "SELECT ward_name,ward_id FROM ward_master";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
if ($_GET['ward']==$row["ward_id"]) {
echo '<option selected="selected" value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
} else {
echo '<option value='.$row["ward_id"].'>'.$row["ward_name"].'</option>';
}
}
?>
</select>
You can do something like this:
<select name="sort" >
<option value="inc_patientName"<?php if ($_GET['sort'] == 'inc_patientName') echo ' selected="seleceted"'; ?>>Patient Name</option>
<option value="inc_date"<?php if ($_GET['sort'] == 'inc_date') echo ' selected="seleceted"'; ?>>Date</option>
<option value="inc_status" <?php if ($_GET['sort'] == 'inc_status') echo ' selected="seleceted"'; ?>>Status</option>
<option value="inc_patientAge"<?php if ($_GET['sort'] == 'inc_patientAge') echo ' selected="seleceted"'; ?>>Age</option>
</select>
Try this:
Use this function in ur script:
function setday(id,elementname)
{
document.getElementById(elementname).value=id;
}
Use this in ur php form, Repeat the same code for year and month dropdowns:
if (isset($_GET['daydropdown']))
{
echo "<script type='text/javascript'>setday('".$_GET['daydropdown']."','daydropdown')</script>";
}
I need to get the text of dropdown and use this to get the first 3 letters of the text. I tried to get the value of row category but it always get the last value in the database.
Help?
<?php
$resultcode = $mysqli->query("SELECT category, id, maincode FROM category GROUP BY id ORDER BY maincode");
$code = '';
while($row = $resultcode->fetch_assoc())
{
$ok = $row['category'];
$code .= '<option value = "'.$row['maincode'].'">'.$row['category'].'</option>';
}
?>
<br/>
Category
<select name="supplier" style="text-transform:uppercase;">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<?php
$myStr = $ok;
// singlebyte strings
$result = substr($myStr, 0, 2);
// multibyte strings
$result1 = mb_substr($myStr, 0, 5);
echo $result.'-'.$result1;
?>
You may try something like this:
Category
<select name="supplier" style="text-transform:uppercase;" onchange = "GetChangedValue(this);">
<option value="">Select</option>
<?php echo $code; ?>
</select>
<script>
function GetChangedValue(e) {
var value = e.options[e.selectedIndex].text;
alert(value);
}
</script>
To get the selected text, you can use Javascript
var element = document.getElementById("mySelectTag");
var selected_text = element.options[element.selectedIndex].text;
To get a substring of a text, use Javascript, for example:
selected_text.substring(0,3)
function change(){
var selectedtext = document.getElementById("idselect").value;
document.getElementById("myTextField").value = selectedtext.substring(0,3);
}
<h1 id="title">Javascript example</h1>
<input type="text" id="myTextField"/>
<select id="idselect" onchange="change()">
<option>Choose one</option>
<option value="BLUE">Blue</option>
<option value="YELLOW">Yellow</option>
<option value="RED">Red</option>
</select>
http://jsfiddle.net/Fx5T8/
I am new with php.I want to change query when some event occur on ComboBox. So that according to that query I retrieve data from database in php.The code is given below:-
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$q = "Select * from Clothes";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} != ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>
When I select blue option of ComboBox my $q(query given in above code) is change to
$q = "Select * from Clothes where colour = 'blue'";
So there should appear only images of clothes having blue colour onpage.
How I reach it?
you need to send ajax request to PHP page. onChange event will trigger ajax request and will change query.
<form method="POST" action="">
<select id="choose-color">
<option value="all">All</option>
<option value="blue">Blue</option>
<option value="black">Black</option>
<option value="white">White</option>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(function(){
$('#choose-color').on('change', function(){
var color = $(this).val();
if(color){
$.ajax({
type: "GET",
url: "index.php", //or your php page
data: { color: color }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
</script>
<?php
$conn = mysqli_connect("localhost","root","123");
mysqli_select_db($conn,"DwtCW");
$whr = ' ';
// check if color is posted on change event
if ( isset($_GET['color'] ) ) {
$whr .= " where colour = '".$color."' ";
}
$q = "Select * from Clothes $whr";
$result = mysqli_query($conn, $q);
if (!$result) {
echo 'Some error';
}
while($row = mysqli_fetch_assoc($result)){
if($row{'Image_url'} == ''){
echo '<div>'
. '<img src='.$row{'Image_url'}.'/>'
.'</div>'
}
?>