So I understand if this may take a while to process but I have a dropdown box and what it's meant to do is if certain selections are clicked then it will fetch info in the database depending on what they selected. My question is, why aren't my if statements working when I have applied a session onto each selection and am fetching them based on the ones clicked.
Here is the HTML:
<div class="button_wrap">
<select name="makeSelectLeft" class="compareButtonSizing" required="required" multiple="multiple">
<option>Make</option>
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?><option value="Mitsubishi1">Mitsubishi</option>
<?php session_start(); $_SESSION['SubOne']="Subaru1" ?><option value="Subaru1">Subaru</option>
<?php session_start(); $_SESSION['ToyOne']="Toyota1" ?><option value="Toyota1">Toyota</option>
</select>
<select name="modelSelectLeft" required="required" multiple="multiple">
<option>Model</option>
<?php session_start(); $_SESSION['LancOne']="Lancer1" ?><option value="Lancer1">Lancer</option>
<?php session_start(); $_SESSION['EvoOne']="Evolution1" ?><option value="Evolution1">Evolution</option>
<?php session_start(); $_SESSION['CamOne']="Camry1" ?><option value="Camry1">Camry</option>
</select>
<select name="yearSelectLeft" required="required" multiple="multiple">
<option>Year</option>
<?php session_start(); $_SESSION['1982 - 1983']="1982 - 1983" ?><option value="1982 - 1983">1982 - 1983</option>
<?php session_start(); $_SESSION['1983 - 1991']="1983 - 1991" ?><option value="1983 - 1991">1983 - 1991</option>
<?php session_start(); $_SESSION['1988 - 1995']="1988 - 1995" ?><option value="1988 - 1995">1988 - 1995</option>
<?php session_start(); $_SESSION['1995 - 2000']="1995 - 2000" ?><option value="1995 - 2000">1995 - 2000</option>
<?php session_start(); $_SESSION['2000 - 2007']="2000 - 2007" ?><option value="2000 - 2007">2000 - 2007</option>
<?php session_start(); $_SESSION['2007 - 2017']="2007 - 2017" ?><option value="2007 - 2017">2007 - 2017</option>
</select>
</div>
Thats where I added in the starts for the sessions. There is a session for each selection. In the PHP I currently have three outputs no matter what options I select. It's supposed to only have one and show one depending on what Make, Model, and Year you have selected.
Here is the PHP:
<?php
session_start();
if (!empty($_SESSION['MitOne']) && ($_SESSION['LancOne']) && ($_SESSION['1982 - 1983'])) {
$MitFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=2");
while ($MitFirstFetch = mysql_fetch_array($MitFirstState)) {
print_r($MitFirstFetch[0]);
}
}
if (!empty($_SESSION['SubOne']) && ($_SESSION['LegOne']) && ($_SESSION['1982 - 1983'])) {
$SubFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=3");
while ($SubFirstFetch = mysql_fetch_array($SubFirstState)) {
print_r($SubFirstFetch[0]);
}
}
if (!empty($_SESSION['ToyOne']) && ($_SESSION['CamOne']) && ($_SESSION['1982 - 1983'])) {
$ToyFirstState = mysql_query("SELECT Max_Speed FROM CarSpecifications WHERE id=4");
while ($ToyFirstFetch = mysql_fetch_array($ToyFirstState)) {
print_r($ToyFirstFetch[0]);
}
}
?>
The main thing I don't understand is why the if statements aren't working. I have tried putting else statements on there and changing the isset/empty variables and all of it. It doesn't seem to work.
Again I apologise for the large amount of info. If someone could help that would be greatly appreciated.
P.S. If someone has a javascript solution they are welcome.
Thank You.
Request-Response is actually simpler than you're trying to attempt.
Your request session in 2nd file will have values initialised for parameters "makeSelectLeft, modeSelectLeft and yearSelectLeft" in the $_REQUEST object. These values are data in "value" attribute of "option".
<option value="Mitsubishi1">
Hence this php snippet is redundant. Remove these from your HTML.
<?php session_start(); $_SESSION['MitOne']="Mitsubishi1" ?>
In your PHP code, $_REQUEST['makeSelectLeft'] will give all values of options selected by user. Similarly you can retrieve data for others. Following that, make your database queries etc.
None of this is being executed properly. As mentioned, you need your session_start(); one time and at the top of the page. Second you need to take advantage of form submission values, not session values. Last, you have to submit the form or use AJAX to process the user's selections. Here is an example (submission of the form is required, you would need to research ajax to do dynamic selections):
<?php
# I'm not convinced you even need this in your example, but you only put it
# once at the top of the page
session_start();
# Process the submission
if(!empty($_POST['action']) && $_POST['action'] == 'do_options') {
# Here is where you do your if conditions based on the post, not session
print_r($_POST['selectleft']);
}
?>
<!--
....html on your page...etc.
-->
<form action="" method="post">
<input type="hidden" name="action" value="do_options" />
<div class="button_wrap">
<select name="selectleft[make]" class="compareButtonSizing" required="required" multiple="multiple">
<option value="">Make</option>
<option value="Mitsubishi1">Mitsubishi</option>
<option value="Subaru1">Subaru</option>
<option value="Toyota1">Toyota</option>
</select>
<select name="selectleft[model]" required="required" multiple="multiple">
<option value="">Model</option>
<option value="Lancer1">Lancer</option>
<option value="Evolution1">Evolution</option>
<option value="Camry1">Camry</option>
</select>
<select name="selectleft[year]" required="required" multiple="multiple">
<option>Year</option>
<option value="1982_1983">1982 - 1983</option>
<option value="1983_1991">1983 - 1991</option>
<option value="1988_1995">1988 - 1995</option>
<option value="1995_2000">1995 - 2000</option>
<option value="2000_2007">2000 - 2007</option>
<option value="2007_2017">2007 - 2017</option>
</select>
</div>
<input type="submit" value="SAVE" />
</form>
Related
I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>
I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output
I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>
Building a football prediction website. I am getting thee Home_team names and away team a names from fixtures table in DBMS, with corresponding drop down boxes for each fixture so that the user can predict the score. I cant get it to work. Grateful for any help!
//establish connection
<?php
$connection = mysql_connect('localhost', 'root', 'password');
mysql_select_db('mls');
$query = "SELECT * FROM fixtures WHERE Fixture_ID BETWEEN '1' and '10' ";
$result = mysql_query($query);
$num = mysql_num_rows($result);
if($num>0){
echo"<table>";
echo "<th>Home Team</th>";
echo "<th>Home Score</th>";
echo "<th>Away Score</th>";
echo "<th>Away Team</th>";
for($count=0;$count<$num; $count++){
$row = mysql_fetch_array($result);
echo"<tr>
<td>".$row['Home_Team']."</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='H".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select >
</td>
<td>
<form id="myForm" method="post" action="process3.php">
<select name="Home_Score">
<select id='A".$count."'>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</td>
<td>".$row['Away_Team']."</td>
</tr>";
}
echo"</table>";
<input type="submit" title="Submit the form">
</form>
}
?>
<html>
<?php
//process3.php file
<?php
include_once('db.php');
$Home_Score = $_POST['Home_Score'];
$Away_Score = $_POST['Away_Score'];
if(mysql_query("INSERT INTO user_prediction VALUES('$Home_Score', '$Away_Score')")){
$result = "Successfully Inserted";
else
$result = "Insert failed";
?>
//myscript.js file
?>
$("#sub").click(function(){
$.post( $("#myForm).attr("action"), $("#myForm:input").serializeArray(),
function (info){$("#result").html(info);});
});
$("#myForm").submit(function(){
return false;
});
While there is plenty of things that could be causing problems, notice here:
<select name="Away_Score">
//count id for unique values in dropdown
<select id='A".$count."'>
$count will literally be represented here as the string "$count", due to this code not being contained in PHP tags. Try correcting instances of code similar to this to something like below:
<?php
echo '<select name="Away_Score">';
//count id for unique values in dropdown
echo '<select id="A' . $count . '">';
?>
I see some problems there..
you switch between PHP and HTML appearently without knowing what
is what or how you start PHP and end it.
Your table is messed
up. You open a table, but in mid you just forget about it. you dont
close your td-tags or your table.
your select is messed up. You
have 2 select tags, one of which has even unescaped php-code written
in it.
your JS click-event does not trigger, because you named
it wrong.
Apart from you using mysql_-functions, which are deprecated and will stop working in newer PHP vewrsions, the list goes on...
In short: This code is a complete mess. Erasing this and starting all over with a clear head would be the best option.
To digress a bit, I honestly think that for an app of that size you should be employing some open source PHP packages. Sorry I can't comment yet so had to leave as an answer
I'm learning html and php, I have a mysql DB employees where there is a table called Employees_hired, which stores id, name, department and type of contract. I want to make a drop down list of employees who belong to a type of department and a specific contract type. In the code would be something like:
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<?php $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()"> <!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()"> <!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<?php if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
The question I have is: how to get the selected values from the first drop-down lists (type_hire and department) for use in the query and fill the drop down list of employees. I know how to fill a dropdown list by querying the DB (what I learned in an online course) but I do not know how to take the values from the dropdown lists and use them in my practice. I read that I can use "document.getElementById (" id "). Value" to give that value to the variable in the query, but nowhere explained in detail how. I am new to web programming and my knowledge of Javascript are poor. Can anyone tell me the best way to do this?. It is possible only using html and php or I have to use javascript?
So you have the onchange in there and that's a start. The onchange is referencing a JavaScript function that you don't show. There are a couple quick ways to approach this:
Post the form to itself (as you have chosen) or
use ajax (possibly via jQuery for quickness).
(both of these examples don't address how you are accessing the database)
1)
Using your run function:
<script type="text/javascript">
function run(){
document.getElementById('form1').submit()
}
</script>
Additional PHP:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
echo "<option value=\"{$row_list['name']}\">{$row_list['name']}</option>";
}
}
else
{
echo "<option>Please choose a department and a type of hire</option>";
}
?>
2)
<script type="text/javascript">
function run(){
$.post('get_employees.php',$('form1').serialize(),function(data){
var html = '';
$.each(data.employees,function(k,emp){
$('select[name="employees"]').append($('<option>', {
value: emp.name,
text: emp.name
}));
.html(html);
},"json");
}
</script>
And get_employees.php would contain something like:
<?php
if (isset($_POST['department']) && isset($_POST['type_hire']))
{
$value_of_department_list = $_POST['department'];
$value_of_type_hire = $_POST['type_hire'];
$return = array();
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')");
while($row_list=mysql_fetch_assoc($list))
{
$return[]['name'] = $row_list['name'];
}
echo json_encode($return);
}
?>
Note, these are just quickly written examples. A lot more could/should be done here.
Heres a modified jQuery version of your code. (With some cleanup)
<html>
<head>
<title>Dynamic Drop Down List</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="<? $_SERVER['PHP_SELF']?>">
department:
<select id="department" name="department" onchange="run()">
<!--Call run() function-->
<option value="biology">biology</option>
<option value="chemestry">chemestry</option>
<option value="physic">physic</option>
<option value="math">math</option>
</select><br><br>
type_hire:
<select id="type_hire" name="type_hire" onchange="run()">
<!--Call run() function-->
<option value="internal">Intenal</option>
<option value="external">External</option>
</select><br><br>
list of employees:
<select name='employees'>
<option value="">--- Select ---</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("employees_hired");
$list=mysql_query("SELECT name FROM usuario WHERE (department ='". $value_of_department_list ."') AND (contrasena ='". $value_of_type_hire."')";);
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<?php echo $row_list['name']; ?>">
<? if($row_list['name']==$select){ echo $row_list['name']; } ?>
</option>
<?php
}
?>
</select>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<!--[ I'M GOING TO INCLUDE THE SCRIPT PART DOWN BELOW ]-->
</body>
</html>
Now I cleaned up the tags, and added a hotlink to jQuery using googleapis free cdn. Next is the actual javascript. Btw. DO NOT USE THE MYSQL_* FUNCTIONS IN PHP. They are depreciated. Check out http://php.net/manual/en/mysqlinfo.library.choosing.php for more info on that. On to the scripting...
<script type="text/javascript">
$('#type_hire').change(function() {
var selected = $('#type_hire option:selected'); //This should be the selected object
$.get('DropdownRetrievalScript.php', { 'option': selected.val() }, function(data) {
//Now data is the results from the DropdownRetrievalScript.php
$('select[name="employees"]').html(data);
}
}
</script>
Now I just freehanded that. But I'll try and walk you though it. First we grab the "select" tag that we want to watch (the hashtag means find the element by ID). Then we grab the selected option within that. Next we run a AJAX call to preform a GET on the page "DropdownRetrievalScript.php" which you would create. What that script should do is take the GET variable "option" and run it through the database. Then have it echo out the "option" tags. Our javascript stuff then takes those results and plugs them directly into the select tag with the name attribute of employees.
Remember that AJAX is just like inputing that url into your browser. So the data variable is literally whatever code or text that url would display. It can be Text, HTML, JSON, XML, anything.