Mysql
 sql >> Database >  >> RDS >> Mysql

Compila il menu a discesa HTML/PHP in base alla prima selezione a discesa

potresti creare un file PHP con la richiesta e chiamarlo con AJAX.

getSubCategory.php

<?php
$category = "";
if(isset($_GET['category'])){
    $category = $_GET['category'];
}

/* Connect to the database, I'm using PDO but you could use mysqli */
$dsn = 'mysql:dbname=my_database;host=127.0.0.1';
$user = 'my_user';
$password = 'my_pass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

$sql = 'SELECT sub_category_name as subCategory FROM t_menu_category WHERE category_name = :category';
$stmt = $dbh->prepare($sql);
$stmt->bindValue(':category', $category);
$stmt->execute();

return  json_encode($stmt->fetchAll());

e aggiungi alcuni jquery da catturare quando viene selezionata una categoria e chiedi al server la sottocategoria corrispondente:

<script>
    $(document).ready(function () {
        $('#item_category').on('change', function () {

            //get selected value from category drop down
            var category = $(this).val();

            //select subcategory drop down
            var selectSubCat = $('#item_sub_category');

            if ( category != -1 ) {

                // ask server for sub-categories
                $.getJSON( "getSubCategory.php?category="+category)
                .done(function( result) {    
                    // append each sub-category to second drop down   
                    $.each(result, function(item) {
                        selectSubCat.append($("<option />").val(item.subCategory).text(item.subCategory));
                    });
                    // enable sub-category drop down
                    selectSubCat.prop('disabled', false);                
                });

            } else {                
                // disable sub-category drop down
                selectSubCat.prop('disabled', 'disabled');
            }
        });    

    });
</script>

aggiungi anche un valore alla tua prima opzione:

<option value="-1" selected="selected">-- Select Category --</option>