簡體   English   中英

如何在一個 select 選項中獲取選定值,並在此基礎上,從 MySQL 表中獲取數據,以相同形式顯示另一個 select 選項

[英]How to get selected value in one select option and based on that, fetch data from MySQL table to show another select option in the same form

在我的 web 頁面中,我在一個表單中有兩個 select 選項。 第一個 select 選項是使用 PHP 從 MySQL 表中獲取的類別,並且工作正常。 但是第二個 select 選項顯示了需要根據用戶選擇的類別選項從 MySQL 表中獲取的子類別。 我不知道 ajax、jQuery 代碼與 MySQL 數據庫一起使用。 這是我的代碼

第一個 select 選項(工作正常)

<select class="form-control"  name="catid" required>
    <option value="">select</option>
       <?php 
        $sql="select cat_id,cat_name from tbl_categories";
        $query=mysqli_query($conn,$sql);
        while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){ ?>
       <option value="<?php echo $row['cat_id'];?>"><?php echo ($row['cat_name']); ?></option>
       <?php 
         }
         if(isset($_POST['catid'])){
          $cid=$_POST['catid'];
         }
        ?>
</select>

第二個 select 選項(不工作)

<select class="form-control"  name="subcatid" required>
    <option value="">select</option>
        <?php 
            $sql2="select s_id,subcat_name from tbl_subcategories where cat_id='$cid' order by subcat_name";
             $query2=mysqli_query($conn,$sq2);
             while($row2 = mysqli_fetch_array($query2, MYSQLI_ASSOC)){ ?>
             <option value="<?php echo $row2['s_id'];?>"><?php echo ($row2['subcat_name']); ?></option>
         <?php } ?>
  </select>

"chained select menus"的想法之前已經介紹過很多次,可以通過不同的方式實現,但其本質如下所示。 主 select 菜單具有分配給它的change事件處理程序,該處理程序向某處的某些 PHP 腳本觸發 ajax 請求。 在下面的代碼中,ajax 請求被發送到同一頁面,但它可能是一個單獨的文件。 The target php script intercepts the POST request and uses the supplied POST data to build a new SQL query which is executed and the results processed to generate, in this case, a string of HTML data which is sent back to the ajax callback. 而不是使用現在老式的XMLHttpRequest下面使用fetch api還必須注意,您的代碼容易受到 SQL 注入的影響 - 因此您必須學習使用准備好的語句

以下內容均未經過測試,因此可能存在小錯誤..但它應該為您指明正確的方向。 聖誕快樂。

<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['catid'],
        $_POST['action']
    )){
        ob_clean();
        
        if( $_POST['action']=='get-sub-category' ){
            $html='';
        
            $sql='select `s_id`, `subcat_name` from `tbl_subcategories` where `cat_id`=? order by `subcat_name`';
            $stmt=$conn->prepare( $sql );
            $stmt->bind_param('s',$_POST['catid']);
            $stmt->execute();
            $stmt->store_result($sid,$name);
            
            
            while( $stmt->fetch() ) $html.=sprintf('<option value="%s">%s',$sid,$name);
            $stmt->free_result();
            $stmt->close();
            
            exit( $html );
        }
    }
?>
<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title></title>
    </head>
    <body>
        <select class="form-control"  name="catid" required>
            <option selected hidden disabled>select
            <?php
                $sql='select `cat_id`, `cat_name` from `tbl_categories`';
                $res=$conn->query( $sql );
                
                while( $row = $res->fetch_assoc() ){
                    printf(
                        '<option value="%s">%s',
                        $row['cat_id'],
                        $row['cat_name']
                    );
                }
            ?>
        </select>

        <select name='subcatid' class='form-control'>
            <option selected hidden disabled>Please select
        </select>
        
        <script>
            document.querySelector('select[name="catid"]').addEventListener('change',function(e){
                
                let fd=new FormData();
                    fd.set('catid',this.value);
                    fd.set('action','get-sub-category');
                    
                fetch(location.href,{method:'post',body:fd })
                    .then(r=>r.text())
                    .then(html=>{
                        let oSelect=document.querySelector('select[name="subcatid"]');
                        let options=oSelect.querySelector('option:not(disabled)');
                            options.forEach(option=>oSelect.removeChild(option))
                        
                        oSelect.inserAdjacentHTML('beforeend',html);
                    })

            });
        </script>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM