Onchange select another mysql query

That being said, I need help on onchange. I have a select tag and I need to make another mysql query when I select something from the select list. Example:

<select name="list">


and then when I choose cars

it does it

$query="select * from table where type='cars'";


and if I choose trucks


$query="select * from table where type='trucks'";


and so on ...
then I need to display the result in a div in a list example

<select name="list">
<div> this is where I need to display results from query</div> 


Please, help!!!


source to share

3 answers

If you want to change the result to ajax:


 <select id="list" name="list">





in JS file:

$(document).ready(function() {
  $('#list').change(function() {
var selected=$(this).val();
  $.get("change_query.php?selected="+selected, function(data){



and you have to create a change_query.php file and your query and code in it and return the result in it

$type = $_POST["selected"];

$query="select * from table where type='".$type."'";


print the result here ....;

  • Tell me if you need any help, I just walked you through JQuery not in all the code.


You have to add SELECT code to the form with the attribute method

set to post

and also the submit button of course. Php will then get the value of these INPUTS and do whatever you want.

   $term = $_POST['list'];

In order to prevent unwanted queries or injection add an array with those terms and
check if the posted value is in this array:

    $terms = array("cars" , "trucks");
    if(!array_key_exists($term , $terms))
     die(); //bad bad bad boy.

    $query = "select * from table where type='$term'";




you can use






All Articles