使用html表单中的onchange事件在php中执行Sql Query [复制]

This question already has an answer here:

I have a html php file. in this file i have a form containing two select boxes employee department and employee branch. if i click the employee department select box it should execute a sql query using onchange event and show the selected department. The php code and html code is in same file. i tried this code

file name : Search.php

<?php
include("config.php");
$dept= (isset($_POST['dept'])) ? $_POST['dept'] : '';
$branch= (isset($_POST['branch'])) ? $_POST['branch'] : '';
?>

<html>
<body>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>"    name="quick_search" id="quick_search"   method = "POST" enctype="multipart/form-data">

<select size="1" name="dept" id="dept" onchange="this.form.submit();" <?php $sql = "SELECT * FROM users WHERE dept = '$dept'"; $qry = mysql_query($sql); ?>>
<option value="select">select</option>
<option value="purchase">purchase</option>
<option value="Sales">sales</option>
<option value="production">production</option>
<option value="accounts">accounts</option>
</select>

<select size="1" name="branch" id="branch" onchange="this.form.submit();" <?php $sql = "SELECT * FROM users WHERE branch = '$branch'"; $qry = mysql_query($sql); ?>>
<option value="select">select</option>
<option value="salem">salem</option>
<option value="chennai">chennai</option>
<option value="kovai">kovai</option>
<option value="namakkal">namakkal</option>
</select>

<?php
while($userdetails = mysql_fetch_array($qry))
{
$userfirstname = $userdetails['firstname'];
$userbranch = $userdetails['branch'];
$userdepartment = $userdetails['department'];
$usersalary = $userdetails['salary'];
}
?>

</form>

</body>
</html>
</div>

Unfortunately this isn't as simple as you would like. Though it's true that you can use php to generated html, they're not so intrinsically linked as all that.

When your user first opens the page, the php will generate the html then send it to their browser. Now that link between the php and the html is severed. If you want to then update the html by getting more information from the server, you need to make a new call to the server and replace the part you need changed. So really you want to use javascript, and in particular, ajax.

Ajax is made quite simple with jQuery, or other javascript frameworks, but if you want to make a call with pure javascript, have a look at this question:

How to make an AJAX call without jQuery?

You could make a call to a php page which fetches the data and sends it back (as JSON or as generated HTML directly) then use javascript to modify the DOM.