简体   繁体   中英

How can I solve this mysql search query

I'm working on a chained select drop down that pulls data from the database to populate the category combobox while the subcategory combo box populates when an option from the category combobox is selected. The category dropdown box pulls data from database without any issue but I am having problems with getting the subcategorycombo box select data from database based on the 'id' of the option selected in the category combo box.Any help pls?below is my php code and the jquery code that display the data

 <?php 
    include ('../storescripts/connection.php');

      function ShowCategory(){
    $sql = "SELECT * FROM category";
   $res = mysql_query($sql) or die(mysql_error());
   $category = '<option value="0">Choose...</option>';
     while($row = mysql_fetch_array($res))
     {
         $category .= '<option value = "'.$row['category_id'].'"> '.$row['category_name']. ' </option>';
         }
         return $category;
   }

   function ShowSubCategory(){
         if (!isset($_POST['id'])) 
        {
        //If not isset -> set with dumy value 
        $_POST['id'] = ""; 

            } 

       $sql1 = "SELECT * FROM subcategory WHERE category_id = '$_POST[id]'";    
       $res1 = mysql_query($sql1) or die(mysql_error());   
       $subcategory = '<option value="0"> Choose...</option>';
       while($row = mysql_fetch_array($res1)){

             $subcategory .= '<option value="'.$row['subcategory_id'].'"> '.$row['subcategory_name'].' </option>';

           }
           return $subcategory;
       }

?>

//jquery code

 <script type="text/javascript">
 $(document).ready(function() {

 $("select#category").change(function(){
var id = $("select#category option:selected").attr('value');
 $.post("select_subcat.php", {id:id}, function(data){
    $("select#subcategory").html(data);
    });
 });

 });
 </script>

Try to narrow down what could be the problem. Have PHP print out the SQL statements to the page when you make a selection.

Then you can feed that exact statement into MySQL (through command line or via phpmyadmin) and see if you get the results you want. If you do, then the problem is later down the line. What do you see?

I will agree with earlier poster - if the $_POST id is not set, you fill it with ""? That probably won't get any results.

One last note: at very least use mysql_real_escape_string() before you ever touch any $_POST or $_GET variables. You are opening your site up to a number of SQL injection attacks otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM