2

Below is a php/mysqli code where it is suppose to insert the courseid and module id into the database, then perform a query to select the course details to find the course details of the inserted course and it then finally runs a final query to ensure the courseid and moduleid which was inserted is in the database.

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
     // connect to the database
     include('connect.php');

      /* check connection */
      if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
      }

    $courseid = (isset($_POST['courses'])) ? $_POST['courses'] : ''; 
    $moduleid = (isset($_POST['moduleid'])) ? $_POST['moduleid'] : '';  
    $moduleno = (isset($_POST['moduleno'])) ? $_POST['moduleno'] : '';  
    $modulename = (isset($_POST['modulename'])) ? $_POST['modulename'] : '';    

    var_dump($courseid);

    $insertsql = "
    INSERT INTO Course_Module
    (CourseId, ModuleId)
    VALUES
    (?, ?)
    ";
    if (!$insert = $mysqli->prepare($insertsql)) {
    // Handle errors with prepare operation here
    }                                           

    $insert->bind_param("ii", $courseid, $moduleid);

    $insert->execute();

    if ($insert->errno) {
    // Handle query error here
    }

    $insert->close();

    $coursequery = "
    SELECT DISTINCT CourseNo, CourseName 
    FROM Course c 
    INNER JOIN Course_Module cm 
    ON
    c.CourseId = cm.CourseId
    WHERE cm.CourseId = ?";
    // prepare query
    $coursestmt=$mysqli->prepare($coursequery);
    // You only need to call bind_param once
    $coursestmt->bind_param("i", $courseid);
    // execute query
    $coursestmt->execute(); 
    // get result and assign variables (prefix with db)
    $coursestmt->bind_result($dbCourseNo, $dbCourseName);

    $query = "SELECT CourseId, ModuleId FROM Course_Module WHERE CourseId = ? AND ModuleId = ?";
    // prepare query
    $stmt=$mysqli->prepare($query); //line 58 error
    // You only need to call bind_param once
    $stmt->bind_param("ii", $courseid, $moduleid); //line 60 error
    // execute query
    $stmt->execute(); 
    // get result and assign variables (prefix with db)
    $stmt->bind_result($dbCourseId, $dbModuleId);
    //get number of rows
    $stmt->store_result();
    $numrows = $stmt->num_rows();

    if ($numrows == 1){

    echo "<span style='color: green'>The following Module has been added into Course:" . $dbCourseNo . " - " . $dbCourseName . ":<br/>" . $moduleno . " - " . $modulename . "</span>";

    }else{

    echo "<span style='color: red'>An error has occured, Module has not been added into the Course</span>";

    }

            ?>

Ok the problem I am getting with the code above is that it does not perform the insert in both CourseId and ModuleId fields. It just inserts the value 0 for both fields. My question is why is it doing this:

Below are both forms:

$addmodule = "
<form id='detailsForm'>

    <p><strong>Module Details</strong></p>
    <table>
    <tr>
    <th></th>
    <td><input type='hidden' id='idmodule' name='moduleid' value='' /> </td>
    </tr>
    <tr>
    <th>Module ID:</th>
    <td><input type='text' id='nomodule' name='moduleno' readonly='readonly' value='' /> </td>
    </tr>
    <tr>
    <th>Module Name:</th>
    <td><input type='text' id='namemodule' name='modulename' readonly='readonly' value='' /> </td>
    </tr>
    </table>

    </form>
";

$moduleForm = "
<form action='".htmlentities($_SERVER['PHP_SELF'])."' method='post' id='moduleForm'>
{$outputcourse}
{$hiddencourse}
<p><strong>Add Module</strong></p>
<p><strong>Module:</strong> {$moduleHTML} </p>   
</form>";

Below is the code where it uses ajax to navigate to the php code right above the UPDATE to perform the insert into database:

    function submitform() {    

    $.ajax({
        type: "POST",
        url: "insertmoduletocourse.php",
        data: { detailsForm: $('#detailsForm').serialize(), moduleForm : $('#moduleForm').serialize() },
        success: function(html){
            $("#targetdiv").html(html);
            $('#targetdiv').show();

        }
     });        
}

When I perform var_dump($courseid) and var_dump($moduleid), it outputs this: string(0) "" string(0) "".

Below is the code where it displays Courses and Modules in their respective drop down menus:

$courseactive = 1;

    $sql = "SELECT CourseId, CourseNo, CourseName FROM Course WHERE CourseActive = ? ORDER BY CourseNo"; 

    $sqlstmt=$mysqli->prepare($sql);

    $sqlstmt->bind_param("i",$courseactive);

    $sqlstmt->execute(); 

    $sqlstmt->bind_result($dbCourseId, $dbCourseNo, $dbCourseName);

    $courses = array(); // easier if you don't use generic names for data 

    $courseHTML = "";  
    $courseHTML .= '<select name="courses" id="coursesDrop">'.PHP_EOL; 
    $courseHTML .= '<option value="">Please Select</option>'.PHP_EOL;  

    $outputcourse = ""; 
    $hiddencourse = ""; 

    while($sqlstmt->fetch()) 
    { 
    $course = $dbCourseId;
    $courseno = $dbCourseNo;
    $coursename = $dbCourseName; 
    $courseHTML .= "<option value='".$course."'>" . $courseno . " - " . $coursename . "</option>".PHP_EOL;  

    if (isset($_POST['courses']) && ($_POST['courses'] == $course)) {
    $outputcourse .= "<p><strong>Course:</strong> " . $courseno .  " - "  . $coursename . "</p>";
    $hiddencourse .= "<p><input type='hidden' id='hiddencourse' value='". $courseno . " - " . $coursename ."'></p>";
}

    } 

    $courseHTML .= '</select>';  

    $moduleInfo = array();


    //get the form data 
$coursesdrop = (isset($_POST['courses'])) ? $_POST['courses'] : ''; 
$moduleactive = 1;  

$modulequery = "
SELECT
m.ModuleId, m.ModuleNo, m.ModuleName, m.Credits
FROM
Module m
WHERE
m.ModuleId NOT IN (
SELECT cm.ModuleId
FROM Course_Module cm
WHERE cm.CourseId = ?
) AND m.ModuleActive = ?
ORDER BY m.ModuleNo
";

$moduleqrystmt=$mysqli->prepare($modulequery);
// You only need to call bind_param once
$moduleqrystmt->bind_param("ii",$coursesdrop, $moduleactive);
// get result and assign variables (prefix with db)

$moduleqrystmt->execute(); 

$moduleqrystmt->bind_result($dbModuleId,$dbModuleNo,$dbModuleName,$dbCredits);

$moduleqrystmt->store_result();

$modulenum = $moduleqrystmt->num_rows();     

$moduleHTML = '<select name="module" id="modulesDrop">'.PHP_EOL;
$moduleHTML .= '<option value="">Please Select</option>'.PHP_EOL;           

while ( $moduleqrystmt->fetch() ) {

$moduleHTML .= sprintf("<option value='%s'>%s - %s</option>", $dbModuleId, $dbModuleNo, $dbModuleName) . PHP_EOL;   

$moduleData = array();
$moduleData["ModuleId"] = $dbModuleId;
$moduleData["ModuleNo"] = $dbModuleNo;
$moduleData["ModuleName"] = $dbModuleName;
$moduleData["Credits"] = $dbCredits;

array_push($moduleInfo, $moduleData);

}


$moduleHTML .= '</select>';

- UPDATE:

Ajax/jquery below:

 function submitform() {    

        $.ajax({
            type: "POST",
            url: "insertmoduletocourse.php",
            data: { 
        courses:    $('#coursesDrop').val(),
        moduleid:   $('#idmodule').val(),
        moduleno:   $('#nomodule').val(),
        modulename: $('#namemodule').val()
    },
            success: function(html){
                $("#targetdiv").html(html);
                $('#targetdiv').show();

                var selectedOption = jQuery("#modulesDrop option:selected");
                selectedOption.appendTo($("#moduleselect"));

                    //Clear fields
                    jQuery("#idmodule").val("");
                    jQuery("#nomodule").val("");
                    jQuery("#namemodule").val("");
                    jQuery("#credits").val("");
            }
         });        
    }

Below is the $courseHTML echo:

<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" onsubmit="return validation();">
<table>
<tr>
<th>Course: <?php echo $courseHTML; ?></th>
</tr>
</table>
<p><input id="courseSubmit" type="submit" value="Submit Course" name="courseSubmit" /></p>
<div id="courseAlert"></div>
<div id="targetdiv"></div>
</form>
4

1 回答 1

1

In place of var_dump($courseid); put print_r($_POST); and check there
1- if you have a value for courses something like [courses] => 'theCoursesValue'
2- it is not "indented" under other array(key)

// this is a print_r($_POST) plus my comments
Array
(
    [courses] => theCoursesValue                // access this value by $_POST['courses']
                                                // in your case may be empty or inexistent
    [otherkey] => otherValue
    [indented] => Array
        (
            [internalKey] => internalValue
            [courses] => thisOneIsNotDirect     // access this value by $_POST['indented']['courses']
        )

)

update
You can do this way:

$.ajax({
    type: "POST",
    url: "insertmoduletocourse.php",
    data: { 
        // an html field must exist for each one of this, with matching id='...blabla...'
        // may be textbox(text), textarea, hidden.
        // be sure that they were generated using "view source code" on the browser
        // again use print_r($_POST) to check
        courses:    $('#coursesDrop option:selected').val(),   // for selects
        moduleid:   $('#moduleid').val(),
        moduleno:   $('#moduleno').val(),
        modulename: $('#modulename').val()
    },
    success: function(html){
        $("#targetdiv").html(html);
        $('#targetdiv').show();
    }
 });
于 2012-12-11T20:03:52.480 回答