简体   繁体   中英

Fetch value from mysql table and display value as selected in drop down menu

I am developing a very simple course catalog. I am using dynamic select drop down menus to display courses being offered by an specific academy . Initially, I am displaying the full list of courses available in theses select menus with values from mysql database table named courses_selection_list . Then I am selecting courses being offered by academy_id=15 by marking the values selected=selected . In the Jquery/JS you will see that I am making a one time ajax call to file getCourses.php where it then displays the select menus when the page loads.

My problem is the following: I am only able to display one value of the course being offered by academy_id=15 . How can I display them all? Or is there a better approach to this? DEMO

courses_offering.php

<script>
    var option = $('#courses_offered').val();
    showFields(option);

    function showFields(option){ 
        var content = '';
        for (var i = 1; i <= option; i++){
            var content = '';
            for (var i = 1; i <= option; i++){
                (function(i) {
                $.ajax({
                        type: "POST",
                    url: "getCourses.php",
                        data: {
                            value: option
                        },
                        success: function (data) {
                            content += '<div id="course_'+i+'">'
                                +'<label>Course # '+i+'</label><br />'
                                +'<label>Course Name:</label>'
                                +'<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list">'
                                +'<option value="" >--- Select ---</option>"';
                            content += data;
                            content += '</select></div></br>';
                            $('#course_catalog').html(content);
                        }
                    });
                })(i);
            }
            $('#course_catalog').html(content);             
        }
        $('#course_catalog').html(content);
    }
</script>

<select name="courses_offered" id="courses_offered" disabled>
    <?php
    $db_select2  = $db_con->prepare("
        SELECT      academy_id
        FROM        courses_by_academy
        WHERE academy_id = :id
        ");
    if (!$db_select2) return false;
    if (!$db_select2->execute(array(':id' => $id))) return false;
    $courses_count = $db_select2->rowCount();
    echo "<option>----Select----</option>";
    echo "<option value=\"1\"". (($courses_count=="1")?"selected=\"selected\"":"") .">1</option>";
    echo "<option value=\"2\"". (($courses_count=="2")?"selected=\"selected\"":"") .">2</option>";
    echo "<option value=\"3\"". (($courses_count=="3")?"selected=\"selected\"":"") .">3</option>";
    echo "<option value=\"4\"". (($courses_count=="4")?"selected=\"selected\"":"") .">4</option>";
    echo "<option value=\"5\"". (($courses_count=="5")?"selected=\"selected\"":"") .">5</option>";
    ?>
</select>
<div id="course_catalog"></div>  

getCourses.php - courses values

$id = 15;
//get the course list
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();

$data = $course_query->fetchAll();
foreach ($data as $row){
    //select the courses being offered by academy_id=15
    $option = "<option value='".$row["course_id"].":".$row["course_name"]."'";
    $db_select  = $db_con->prepare("
        SELECT academy_id, course_name, course_id, 
               course_start_date, course_end_date
        FROM courses_by_academy
        WHERE academy_id = :id
    ");
    if (!$db_select) return false;
    if (!$db_select->execute(array(':id' => $id))) return false;
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
    if (empty($results)) return false;
    foreach ($results as $value) {
        $result= $value['course_id'];
        if ($result == $row['course_id']) {
            $option .= "selected='selected'";
        }            
    }
    $option .= ">". $row['course_name'] ."</option>";
    //show result
    echo $option;            
}   

Mysql Tables Example:

courses_selection_list

+-----------+-------------------------+
| course_id |       course_name       |
+-----------+-------------------------+
|         1 | Math                    |
|         2 | English                 |
|         3 | Science                 |
|         4 | Other- Not Listed       |
|         5 | Social Studies          | 
|         6 | Home Mac                |  
|         7 | Business Management     | 
|         8 | Psychology              | 
|         9 | Accounting              | 
|        10 | Advanced Networks       |  
|        11 | Information Techonology |  
+-----------+-------------------------+

courses_by_academy

+----+------------+--------------------------+-----------+------------+----------+
| id | academy_id |  course_name             | course_id | start_date |end_date  |
+----+------------+--------------------------+-----------+------------+----------+
|  1 |         15 | Science                  |         3 |2013-12-04  |2013-12-25|
|  2 |         15 | Business Management      |         7 |2013-12-04  |2013-12-25|
|  3 |         15 | Information Technology   |        11 |2013-12-04  |2013-12-25|
+----+------------+--------------------------+-----------+------------+----------+

Desired Result:

在此输入图像描述

Javascript insert into document.ready event

var option = 3,
    $course_catalog = $('#course_catalog');
showFields(option);

function showFields(option){ 
    $course_catalog.html('');
    // request only once
    $.ajax({
        type: "POST",
        url: "getCourses.php",
        async : false,
        data: { 
            value : option
        },
        dataType : 'json',
        contentType : 'application/json',
        success: function (data) {
            for (var i = 1; i <= option; i++){
               // prepare select
                $course_catalog.append('<div id="course_' + i + '"><label>Course # '+i+'</label><br />'
                        +'<label>Course Name:</label>'
                        +'<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list">'
                        +'<option value="" >--- Select ---</option>"'
                        +'</select><br/><p id="date_'+i+'"></p></div></br>');

                var $el = $course_catalog.find('#coursename_' + i), 
                    val = 0,
                    index = 1;
                for(var n in data) {
                    var o = data[n];
                    if (o.academy_id > 0) {
                        if (index == i) {
                            val = o.id + ':' + o.name;
                            $course_catalog.find('#date_'+i).html('Start at: ' + o.start_date + ' until '+o.end_date);
                        }
                        index ++;
                    }
                    $el.append('<option value="' + o.id + ':' + o.name + '">'+o.name+'</option>');
                }
                $el.val(val);
            }
        }
    });
}

PHP code:

header("Content-type: application/json");
$id = 15;
//get the course list
$course_query = $db_con->prepare("
    SELECT 
        t.course_id, t.course_name, IFNULL(lj.academy_id, 0) as academy_id, lj.course_start_date, lj.course_end_date
    FROM courses_selection_list as t
    LEFT JOIN courses_by_academy as lj 
        ON (lj.course_id = t.course_id AND lj.academy_id = :id)
    ORDER BY t.course_id
");
$course_query->execute(array(':id' => $id));
$data = $course_query->fetchAll();

$course_data = array();
foreach ($data as $row) { 
    $course_data[] = array(
       "id" => $row["course_id"],
       "name" => $row["course_name"],
       "academy_id" => $row["academy_id"],
       "start_date" => $row["course_start_date"],
       "end_date" => $row["course_end_date"],
    );
}  // foreach ($data as $row) {
echo json_encode($course_data);

Assume that you have a select box that lists all the academies available:

<select name="academy" id="acadaemy">
  <option value="1">Academy1</option>
    .............................
    .............................
  <option value="15">Academy15</option>
</select>

Then you can bind an onchange event for this select to display the desired courses.

 $('#acadaemy').on('change', function() {
           var option = this.value;
                   $.ajax({
                    type: "POST",
                    url: "getCourses.php",
                    data: {
                            'ac_id': option
                    },
                    success: function (data) {
                                  $('#course_catalog').html(data);
                        }
                    });
});

And in ur getCourses.php

Step 1:  fetch the POST value (here $_POST['ac_id']) and validate it
Step 2:  Get all courses.
Step 3:  Get all courses with specified academy id
Step 4:  Iterate result from step 3 and create each select tag.
Step 5:  Iterate result from Step 2 and create option tags and set selected.
Step 6:  Echo back the result.



<?php
     $id = $_POST['ac_id'];
     //Do something here to validate the post data

    $course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
    $course_query->execute();

$data = $course_query->fetchAll();//All courses here
    $db_select  = $db_con->prepare("
        SELECT academy_id, course_name, course_id, 
               course_start_date, course_end_date
        FROM courses_by_academy
        WHERE academy_id = :id
    ");
$resultStr = '';

if (!$db_select) return false;
    if (!$db_select->execute(array(':id' => $id))) return false;
    $results = $db_select->fetchAll(\PDO::FETCH_ASSOC); // academy specific courses here
    if (empty($results)) return false;
    foreach ($results as $value) { // iterate academy courses
    $resultStr .= '<div class="course">';
    $resultStr .= '<select name="coursename[]" class="course_list">';
          foreach ($data as $row){ // iterate all courses
                        $result .= "<option value='".$row["course_id"].":".$row["course_name"]."'";
            if ($result['course_id'] == $row['course_id']) {
                $resultStr .= " selected='selected'";
            } 
                        $resultStr .= ">". $row['course_name'] ."</option>";
                  }
    $resultStr .= '</select>';
    $resultStr .= '</div>';
    }
echo $resultStr;
exit();
?>

The reason why this doesn't work is that your SQL queries are in the wrong order. You first want to get the courses_by_academy and then get the respective course from the courses_selection_list .

Also your approach to using Javascript in this context is a bit unreasonable, so I have removed it for displaying the dropdowns.

<?php
$id = 15;

//get the course list
$db_select  = $db_con->prepare("
    SELECT academy_id, course_name, course_id, 
           course_start_date, course_end_date
    FROM courses_by_academy
    WHERE academy_id = :id
");
if (!$db_select) return false;
if (!$db_select->execute(array(':id' => $id))) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);

if (empty($results)) return false;
foreach ($results as $value) {

$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();

$data = $course_query->fetchAll();
$i = 0;
foreach ($data as $row){
    $i += 1;

    echo '<div class="courses">';
    echo '<label>Course # <span>', $i, '</span></label><br />';
    echo '<label>Course Name:</label>';
    echo '<select name="coursename[]" class="course_list">';
    echo '<option>--- Select ---</option>"';

    echo "<option value='".$row["course_id"].":".$row["course_name"]."'";
    if ($value['course_id'] == $row['course_id']) {
        echo " selected='selected'";
    }
    echo ">". $row['course_name'] ."</option>";
}   
echo '</select></div></br>';

Note how I used coursename[] as the name for the SELECT: using this the PHP will receive this as an array in the POST request, as $_POST["coursename"] , so that you can use foreach to go through them.

I assume the Javascript is meant to be able to change the number of courses? I would take a different approach here:

$("#courses_offered").on("change", function() {
    var number_of_courses_offered = $('#courses_offered').val();
    var course_divs = $("div.courses");

    if (number_of_courses_offered < 1) {
        course_divs.hide();
        return;
    }

    course_divs.show();

    // to few courses displayed: add another one until the number fits
    while (course_divs.length < number_of_courses_offered) {

        // create an empty course div by using the first one and removing the 
        // selected attribute so that the first item "--- Select" is displayed
        var single_course_div = course_divs.first().clone(true);
        single_course_div.find("option:selected").removeAttr("selected");
        // fix the course number
        single_course_div.find("span").text(course_divs.length + 1);

        // insert it after the last of the divs
        course_divs.last().after(single_course_div);

        course_divs = $("div.courses"); // update for the next while loop
    }

    // too many courses displayed: remove the last ones
    while (course_divs.length > number_of_courses_offered) {
        // remove the last div
        course_divs.last().remove();

        course_divs = $("div.courses"); // update for the next while loop
    }

});

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