Related select inputs - php

Can anybody help me on this. For showing the rezults from an MySql database i have to select school, class, subject, and exam. But listing all the classes or all the exams is not very practical so i want to do another function that when i choose some schools in the first select box it shows me in the second select box only the classes of the selected schools.
My code is:
<div id="allselects">
<form action="viewing.php" method="post" name="filt">
<div class="multsarrange">
<h1 class="choosetext" >Chose Schools</h1>
<select class="multipleselect" name="schools[]" size="8" multiple="multiple" id="shkll">
<?php
$sql = "SELECT * FROM schools ";
$scc=mysql_query($sql);
while ($db_f = mysql_fetch_assoc($scc)) {
$schcd=$db_f['schoolcode'];
$schc=$db_f['schoolname'];
echo "<option value=$schcd >$schc</option>";
}
?>
</select>
</div>
<div class="multsarrange" id="clasaajax">
<h1 class="choosetext" >Chose an Classes</h1>
<select class="multipleselect" name="classes[]" size="8" multiple="multiple" ">
<?php
$c = "SELECT * FROM classes ";
$cl=mysql_query($c);
while ($db_f = mysql_fetch_assoc($cl)) {
$clsc=$db_f['schoolID'];
$claid=$db_f['classID'];
$clay=$db_f['year'];
$clanm=$db_f['className'];
$name=schoolidton($clsc)." ".$clay." ".$clanm;
echo "<option value=$claid >$name</option>";
}
?>
</select>
</div>
<div class="multsarrange">
<h1 class="choosetext" >Chose Subjects</h1>
<select class="multipleselect" name="subjects[]" size="8" multiple="multiple">
<?php
$sb = "SELECT * FROM subjects ";
$sbi=mysql_query($sb);
while ($db_f = mysql_fetch_assoc($sbi)) {
$sbnm=$db_f['subjectName'];
$sbid=$db_f['subjectID'];
echo "<option value=$sbid >$sbnm</option>";
}
?>
</select>
</div>
<div class="multsarrange">
<h1 class="choosetext" >Chose Exams</h1>
<select class="multipleselect" name="exams[]" size="8" multiple="multiple">
<?php
$e = "SELECT * FROM exams ";
$ex=mysql_query($e);
while ($db_f = mysql_fetch_assoc($ex)) {
$id=$db_f['examID'];
$sub=$db_f['subjectID'];
$desc=$db_f['description'];
$year=$db_f['year'];
$data=$db_f['data'];
$exnam=subidton($sub)." - ".$year." - ".$desc." - ".$data;
echo "<option value=$id >$exnam</option>";
}
?>
</select>
</div>
<div id="longsubmit">
</br></br>
<input name="submit" type="submit" value="View" />
</div>
</form>
</div>

What you need to do is the following :
Setup an event listener on the select to listen for the change event - see here
Process the change event by sending the selected value to the PHP script - see here
Using PHP get the selected value and query the database as required (you already do that bit)
Send the associated HTML output or JSON or XML if you just creating a new select list - this is a simple echo
Write the output to the screen using JavaScript - this is either creating a new element based on the reply from the PHP function or inserting the HTML response
There are lots of things within this process - each with multiple options - i suggest you attempt to tackle each one and come back with specific questions if you get stuck

use ajax on abc.php get values or ids of school and make the tags you need and return back the results to the relevant id of html
function get_options(table,id_field,name_field,where_field,field_value,select_id,edit_id){
$('#'+select_id).html('<option>Loading...</option>');
$.ajax({
type: "POST", url: "abc.php", data: "&table="+table+"&id_field="+id_field+"&name_field="+name_field+"&where_field="+where_field+"&field_value="+field_value+ "&edit_id=" + edit_id +"&get_option=1",
complete: function(data){
//alert(data.responseText);
$('#'+select_id).html(data.responseText);
}
});
}

You have to use AJAX inorder to achieve this.
check this
http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php

Related

POST or GET selected value from select option before submit (same page)

I have done searching this question here but there is no suitable answer for my problem. So to be more specific, I have 2 select option which is floor and room. Both selection displayed based on database. So is there a syntax that can get the selected floor id so I can do my query to display the specific room for the selected floor before submit? Here's my code :
<form name="form" method="POST">
<div class="form-group">
<div><label>Floor Name</label></div>
<select class="form-control" id="floorid" name="existfloorname">
<option>None</option>
<?php
$result = $conn->query("select * from floors");
while ($row = $result->fetch_assoc())
{
?><option id="<?php echo $row['floorid'];?>" value="<?php echo $row['floorname']; ?>"><?php echo $row['floorname']; ?></option><?php
}
?>
</select>
</div>
<div class="form-group">
<div><label>Room Name</label></div>
<select class="form-control" name="existroomname">
<option>None</option>
<?php
$result = $conn->query("select * from rooms where floorid = '".GETSELECTEDFLOORID."'");
while ($row = $result->fetch_assoc())
{
?><option value="<?php echo $row['roomname']; ?>"><?php echo $row['roomname']; ?></option><?php
}
?>
</select>
</div>
<input type="submit" name="delete" value="Delete">
</form>
This is how the form looks like
You need to work with AJAX for this. AJAX allows the sending of data from the front(JS) to the back(PHP). JQuery makes this easy by providing you with the .ajax() method. This is how you need to do this:
Note: You will need to use jQuery to do it this way
First, re-arrange your HTML in this manner, notice the select ids:
<form name="form" method="POST">
<div class="form-group">
<div><label>Floor Name</label></div>
<select class="form-control" id="floor_select" name="existfloorname">
<option>None</option>
<?php
$floors = $conn->query("select * from floors");
while ($row = $floors->fetch_assoc()){ ?>
<option value="<?= $row['floorid']; ?>"><?= $row['floorname']; ?></option>
<?php } ?>
</select>
</div>
<div class="form-group">
<div><label>Room Name</label></div>
<select class="form-control" id="room_select" name="existroomname">
<option>None</option>
</select>
</div>
<input type="submit" name="delete" value="Delete">
</form>
Second, create your jQuery ajax call:
$(document).on("change", 'select#floor_select', function(e) {
var floor_id = $(this).val();
$.ajax({
type: "POST",
data: {floor_id: floor_id},
url: 'get_room_list.php',
dataType: 'json',
success: function(json) {
var $el = $("select#room_select");
$el.empty(); // remove old options
$el.append("<option>Please Select</option>");
//iterate through your results and add to your dropdown
$.each(json, function(k, v) {
$el.append("<option value='" + v.id + "'>" + v.roomname + "</option>");
});
}
});
});
Third, create the PHP script that the AJAX call above is looking for.
Call it get_room_list.php:
<?php
$result = $conn->query("select * from rooms where floorid = '" . GETSELECTEDFLOORID . "'");
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
Once all the above is done, you should be able to obtain the information you need. Every time the "Floor Name" select is changed, JS will send a POST request (via AJAX) to PHP and PHP will return the "rooms" result in JSON format, which you then iterate to create your dropdown.
Hope this all makes sense.
Good luck.
You may need AJAX to get list room each floor.

create 2 inter dependent dropdown menu in php

i have this html for that displays 2 dropdown. one is for category and second is for subcategory
<form action="a_insert_product.php" method="post">
<div class="module_content">
<fieldset>
<label>Category</label>
<select name="catname">
<?php
$sql = "SELECT * FROM category";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$catname=$row["catname"];
$catid=$row["id"];
?>
<option value="<? echo $catname.'-'.$catid;?>"><? echo $catname;?></option>
<?}
}?>
</select>
</fieldset>
<fieldset>
<label>Subcategory</label>
<select name="subcatname">
<?php
$sql = "SELECT * FROM subcategory";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result))
{
$subcatname=$row["subcatname"];
$subcatid=$row["id"];
?>
<option value="<? echo $subcatname.'-'.$subcatid;?>"><? echo $subcatname;?></option>
<?}
}?>
</select>
</fieldset>
<fieldset>
<label>Product Name</label>
<textarea rows="2" name="prodname"></textarea>
</fieldset>
</div>
<footer>
<div class="submit_link">
<input type="submit" name="submit" value="Submit" class="alt_btn">
</div>
</footer>
</form>
Although it is working fine but i wish to display the subcategory according to the category that is selected in the category dropdown, i don't have much knowledge regarding javascript. can anyone plz tel how it can be done
You can do it using AJAX, for example, assign an "id" attribute to both your catname and subcatname dropdowns:
<select name="catname" id="category-dropdown">
<select name="subcatname" id="subcategory-dropdown">
And then use some AJAX magic, for example:
<script type="text/javascript">
$("#category-dropdown").change(function() {
var selection_value = $(this).val();
$.post("subcategories.php", { category: selection_value },
function(result){
$.each(result, function(index, subcat) {
var option_html = "<option>" + subcat.name + "</option>";
$("#subcategory-dropdown").append(option_html);
}
},
"json");
});
</script>
Please note that this example uses jQuery, so you will have to add it to your page before using. Also, you will need to create a PHP page that will provide you with the response for subcategories, in this case I have used JSON, which is fairly easy to use.
I would do the following:
On the first dropdown, you'd have an on change handler which checks for what is selected in the dropdown. I would link that to an ajax call which then brings in the correct data to allow you to populate the second dropdown.
Google or search on here "JQuery on change" and "JQuery ajax" - there's tons of resources out there.
This is a different approach to same ends

PHP Form - Highlight multiple selection for SQL query

I'm trying to keep multiple options selected in a dropdown form after being submitted but I can't get it to work. The options don't stay selected. I've seen answers for this using foreach() (Highlighting multiple selections on a form after submitting), however my data comes from a SQL query so I believe I need to use while() to loop through the rows. Any thoughts?
$id7 = $_REQUEST['id7'];// Interest Level
<?php
$getParameter_sql4 = 'SELECT Funds.[Interest Level] FROM Funds GROUP BY Funds.[Interest Level] ORDER BY Funds.[Interest Level]';
$getParameter4 = sqlsrv_query($conn,$getParameter_sql4);
?>
<form action="/Reports/FundStatistics.php" method="get">
<select name="id7[]" multiple size="4">
<?php while ($row4 = sqlsrv_fetch_array($getParameter4, SQLSRV_FETCH_ASSOC)) { ?>
<option <?php if (in_array($row4['Interest Level'],$id7)) { echo 'selected="selected"';}?> value="'<?php echo $row4['Interest Level']; ?>'"><?php echo $row4['Interest Level']; ?></option><?php }?>
</select>
<input type="submit" VALUE="Update" /></form>

Dropdown List Value From SQL in PHP

I want to do this function in php. i have two fields, one is text box and an
other one is drop down list. Drop down list contains values from sql. When one of the value is selected from the drop down list i want the text box to be filled according to the option which is selected.
Following is the drop down list code,
<td>Test Group ID</td>
<td><select id="testgroupid" name="testgroupid" style="column-width:35">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH)){
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select></td>
According to the id,I want textbox to be filled, How can i do this ? Pls help friends.
<tr>
<td>Test Group Name</td>
<td><input type="text" name="testgroupname" id="zipsearch" value="<?php echo $testgroupname; ?> "></td>
</tr>
If you want your textbox to be filled immediately after the dropdown selection changes, the simplest way is to use javascript:
<td><select id="testgroupid" name="testgroupid" style="column-width:35"
onchange='document.getElementsByName("testgroupname")[0].value =
document.getElementById("testgroupid").options[e.selectedIndex].value;'>
You need JavaScript for that. Use jQuery (or your favorite library) and bind an event listener to the combobox.
Example with jQuery:
$("#myCombo").change(function(e){
$("myTextField").val( $("#myCombo").val() );
});
I have one suggestion which involves jQuery. I do not know if you are using this library, but I am posting it anyway :)
<script type="text/javascript">
$(function() {
$("#testgroupid").change(function{
$("#zipsearch").text($(this option:selected).val();
});
});
</script>
On change event on the dropbown-box, this function fires, and sets the zipsearch-input accordingly.
I am not sure where $testgroupname comes from but I take it you would like to get that value upon selection in the dropdown. If you don´t have the value available on the client you have to retrieve it from the server somehow.
You can´t use PHP to fill the text box since you do not send your posts when an options is selected in the dropdown. There are many alternatives on how to solve this. I would personally use Ajax to fill the textbox without posting to server.
Good place to start:
http://buffernow.com/2012/08/cascading-dropdown-ajax/
html
<select id="testgroupid" name="testgroupid"
style="column-width:35" onChange=filltext();>
javascript
function filltext()
{
var e = document.getElementById("testgroupid");
var group = e.options[e.selectedIndex].text;
document.getElementById("zipsearch").value= group ;
}
your php code is wrong here
<option value="<?=$res['Id'];?>"><?=`$res['Id']`;?></option>
change to
<option value="<?=$res['Id'];?>"><?=$res['GROUP_NAME'];?></option>
Try like this
<script>
function selecteditem(selectedval)
{
jQuery.post("<?php echo JURI::root().'test.php'?>", { id: selectedval },
function(data) {
jQuery('.zipsearch').val(data);
});
}
</script>
//test.php on the root
<?php
$val=$_POST['id'];
//do what you want with $val
//and say final output is in variable $result than echo it
echo $result;
?>
<!--html code here-->
<select id="testgroupid" name="testgroupid" style="column-width:35" onclick="selecteditem(this.value);">
<option value="<?php echo $testgroupid;?>"><?php echo $testgroupid;?></option>
<?php
$x=new con();
$x->connect();
$retval = "select distinct(Id) from testgroupmaster";
$sql1 = mysql_query($retval) or die (mysql_error());
while($res=mysql_fetch_array($sql1, MYSQL_BOTH))
{
?>
<option value="<?=$res['Id'];?>"><?=$res['Id'];?></option>
<?
}
?>
</select>
<input type="text" name="testgroupname" id="zipsearch" class="zipsearch" value="<?php echo $testgroupname; ?> ">
<?php
// Assume $db is a PDO object
$dbh = new PDO('mysql:host=localhost;dbname=populatedropdown', "root", "");
$query = $dbh->query("select * from position"); // Run your query
echo '<form action="populate.php" method="get" name="send3">';
echo '<select name="populate">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.$row['name'].'">'.$row['name'].'</option>';
}
echo '</select>';// Close your drop down box
echo '</form>';
?>
<script language="JavaScript">
function send_input1(){
document.send1.input4.value = document.send3.populate.value;
}
</script>
<form name="send1" action=javascript:send_input1()>
<p><input type=submit value=Enter>
</p><input size=30 name="input4">
</form>

List option values fail to insert into the database

I've created a php form to insert values into a database.
One of my form options is a dynamic list populated with fields from another table.
I first created the form without the dynamic option, and all data inserted just fine (and still does).
Now I'm attempting to include the code below, and while it displays the option values properly, the value fails to insert. Any advice?
<?php
/*
* LIST ALL CATEGORIES
****************************************/
include('../dbconnection.php');
$query = 'SELECT category_id, category_name FROM ingredient_categories';
$result = mysql_query($query);
echo '<select>';
while ($ingredientCategoryOption = mysql_fetch_array($result)) {
echo '<option value="'.$ingredientCategoryOption[category_id].'">'.$ingredientCategoryOption[category_name].'</option>';
}
echo '</select>';
?>
I had created something similar yesterday. The $polls array is passed to the view in CodeIgniter in the $this->load->view('poll.php', $data['polls']), while you do it in the page itself. However, you can have the general idea.
<FORM id="formPoll" class="question" name="createpoll" action="<?php echo base_url()?>index.php/poll/selectOption/" method="POST">
<select name="poll_list">
<?php
foreach($polls as $poll){
echo "<option name='poll_table'>$poll->name</option>";
}
?>
</select>
<div id="input">
Poll name: <input type="text" name="name"></input>
Title: <input type="text" name="title"></input>
</div>
<div id="options">
Option: <input type="text" name="option"></input>
</div>
<input type="submit"></input>
</FORM>
Some ideas:
Check if $results is not empty before using it
Give your <select> form a name, as I showed above
Check if $ingredientCategoryOption is not null or is something returned.
Check your database connection

Categories